This repository has been archived on 2024-09-20. You can view files and clone it, but cannot push or open issues or pull requests.
musicapp/worker.moon
2019-06-28 19:37:35 -07:00

31 lines
917 B
Plaintext

lock = require "resty.lock"
import Tags, Tracks from require "models"
import escape_literal from require "lapis.db"
add_job = (interval, name, fn, init) ->
run = (premature, arg) ->
if premature return
thread_lock = lock\new "worker". { timeout: 0, exptime: interval }
if thread_lock\lock "t#{name}"
time_lock = lock\new "worker", { exptime: interval }
if time_lock\lock "t#{name}"
arg = fn(arg)
thread_lock\unlock!
ngx.timer.at(interval, run, arg)
ngx.timer.at(0, run, init)
update_tag_counts = (id=1) ->
if tag = Tags\find(:id)
tag_pattern = escape_literal tag.name
tag_pattern = "'% #{tag_pattern\sub 2, -2} %'"
count = Tracks\count "tags LIKE #{tag_pattern}"
tag\update(:count)
next_tag = Tags\select "WHERE id > ? ORDER BY id ASC LIMIT 1", id
if next_tag = next_tag[1]
return next_tag.id
add_job 60, "tags", update_tag_counts