addRepeatableJob-2.lua 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. --[[
  2. Adds a repeatable job
  3. Input:
  4. KEYS[1] 'repeat' key
  5. KEYS[2] 'delayed' key
  6. ARGV[1] next milliseconds
  7. ARGV[2] msgpacked options
  8. [1] name
  9. [2] tz?
  10. [3] pattern?
  11. [4] endDate?
  12. [5] every?
  13. ARGV[3] legacy custom key TODO: remove this logic in next breaking change
  14. ARGV[4] custom key
  15. ARGV[5] prefix key
  16. Output:
  17. repeatableKey - OK
  18. ]]
  19. local rcall = redis.call
  20. local repeatKey = KEYS[1]
  21. local delayedKey = KEYS[2]
  22. local nextMillis = ARGV[1]
  23. local legacyCustomKey = ARGV[3]
  24. local customKey = ARGV[4]
  25. local prefixKey = ARGV[5]
  26. -- Includes
  27. --- @include "includes/removeJob"
  28. local function storeRepeatableJob(repeatKey, customKey, nextMillis, rawOpts)
  29. rcall("ZADD", repeatKey, nextMillis, customKey)
  30. local opts = cmsgpack.unpack(rawOpts)
  31. local optionalValues = {}
  32. if opts['tz'] then
  33. table.insert(optionalValues, "tz")
  34. table.insert(optionalValues, opts['tz'])
  35. end
  36. if opts['pattern'] then
  37. table.insert(optionalValues, "pattern")
  38. table.insert(optionalValues, opts['pattern'])
  39. end
  40. if opts['endDate'] then
  41. table.insert(optionalValues, "endDate")
  42. table.insert(optionalValues, opts['endDate'])
  43. end
  44. if opts['every'] then
  45. table.insert(optionalValues, "every")
  46. table.insert(optionalValues, opts['every'])
  47. end
  48. rcall("HMSET", repeatKey .. ":" .. customKey, "name", opts['name'],
  49. unpack(optionalValues))
  50. return customKey
  51. end
  52. -- If we are overriding a repeatable job we must delete the delayed job for
  53. -- the next iteration.
  54. local prevMillis = rcall("ZSCORE", repeatKey, customKey)
  55. if prevMillis then
  56. local delayedJobId = "repeat:" .. customKey .. ":" .. prevMillis
  57. local nextDelayedJobId = repeatKey .. ":" .. customKey .. ":" .. nextMillis
  58. if rcall("ZSCORE", delayedKey, delayedJobId)
  59. and rcall("EXISTS", nextDelayedJobId) ~= 1 then
  60. removeJob(delayedJobId, true, prefixKey, true --[[remove debounce key]])
  61. rcall("ZREM", delayedKey, delayedJobId)
  62. end
  63. end
  64. -- Keep backwards compatibility with old repeatable jobs (<= 3.0.0)
  65. if rcall("ZSCORE", repeatKey, legacyCustomKey) ~= false then
  66. return storeRepeatableJob(repeatKey, legacyCustomKey, nextMillis, ARGV[2])
  67. end
  68. return storeRepeatableJob(repeatKey, customKey, nextMillis, ARGV[2])