local rcall = redis.call
local repeatKey = KEYS[1]
local delayedKey = KEYS[2]
local waitKey = KEYS[3]
local pausedKey = KEYS[4]
local metaKey = KEYS[5]
local prioritizedKey = KEYS[6]
local nextMillis = tonumber(ARGV[1])
local jobSchedulerId = ARGV[2]
local timestamp = tonumber(ARGV[5])
local prefixKey = ARGV[6]
local producerId = ARGV[7]
local jobOpts = cmsgpack.unpack(ARGV[4])
local prevMillis = rcall("ZSCORE", repeatKey, jobSchedulerId)
if prevMillis then
prevMillis = tonumber(prevMillis)
local schedulerKey = repeatKey .. ":" .. jobSchedulerId
local schedulerAttributes = rcall("HMGET", schedulerKey, "name", "data", "every", "startDate", "offset")
local every = tonumber(schedulerAttributes[3])
local now = tonumber(timestamp)
if not every and jobOpts['repeat'] and jobOpts['repeat']['every'] then
every = tonumber(jobOpts['repeat']['every'])
end
if every then
local startDate = schedulerAttributes[4]
local jobOptsOffset = jobOpts['repeat'] and jobOpts['repeat']['offset'] or 0
local offset = schedulerAttributes[5] or jobOptsOffset or 0
local newOffset
nextMillis, newOffset = getJobSchedulerEveryNextMillis(prevMillis, every, now, offset, startDate)
if not offset then
rcall("HSET", schedulerKey, "offset", newOffset)
jobOpts['repeat']['offset'] = newOffset
end
end
local nextDelayedJobId = "repeat:" .. jobSchedulerId .. ":" .. nextMillis
local nextDelayedJobKey = schedulerKey .. ":" .. nextMillis
local currentDelayedJobId = "repeat:" .. jobSchedulerId .. ":" .. prevMillis
if producerId == currentDelayedJobId then
local eventsKey = KEYS[9]
local maxEvents = getOrSetMaxEvents(metaKey)
if rcall("EXISTS", nextDelayedJobKey) ~= 1 then
rcall("ZADD", repeatKey, nextMillis, jobSchedulerId)
rcall("HINCRBY", schedulerKey, "ic", 1)
rcall("INCR", KEYS[8])
local templateData = schedulerAttributes[2] or ARGV[3]
if templateData and templateData ~= '{}' then
rcall("HSET", schedulerKey, "data", templateData)
end
local delay = nextMillis - now
if delay < 0 then
delay = 0
end
jobOpts["delay"] = delay
addJobFromScheduler(nextDelayedJobKey, nextDelayedJobId, jobOpts, waitKey, pausedKey, KEYS[12], metaKey,
prioritizedKey, KEYS[10], delayedKey, KEYS[7], eventsKey, schedulerAttributes[1], maxEvents, ARGV[5],
templateData or '{}', jobSchedulerId, delay)
if KEYS[11] ~= "" then
rcall("HSET", KEYS[11], "nrjid", nextDelayedJobId)
end
return nextDelayedJobId .. "" else
rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "duplicated", "jobId", nextDelayedJobId)
end
end
end