【发布时间】:2016-11-22 19:28:15
【问题描述】:
是否有可能在服务器端 Swift 框架(最好是 Kitura)上调度任务?
我需要安排任务;例如,每天凌晨 3 点擦除数据库。
【问题讨论】:
是否有可能在服务器端 Swift 框架(最好是 Kitura)上调度任务?
我需要安排任务;例如,每天凌晨 3 点擦除数据库。
【问题讨论】:
至少在 Kitura 中,我们没有为此提供特殊功能。
您可以考虑使用 Dispatch,这对于您每天凌晨 3 点删除数据库的示例非常有效。您可以创建一个 DispatchSourceTimer,它在某个时间间隔后一次或重复地分派一些代码。
DispatchSourceTimer.scheduleOneshot(deadline: DispatchTimer, leeway: DispatchTimeInterval)
DispatchSourceTimer.scheduleRepeating(deadline: DispatchTime, interval: DispatchTimeInterval, leeway: DispatchTimeInterval)
【讨论】:
error: use of undeclared type 'DispatchSourceTimer' 这样的错误。有什么技巧可以让 Dispatch 在 Heroku / Unix 上运行?
我花了一些时间才完成这项工作,所以这就是我所拥有的:
let timer = DispatchSource.makeTimerSource()
timer.setEventHandler() {
// Coded I want to execute after a delay
}
let now = DispatchTime.now()
let delayInSeconds:UInt64 = 5
let deadline = DispatchTime(uptimeNanoseconds: now.uptimeNanoseconds + delayInSeconds*UInt64(1e9))
timer.scheduleOneshot(deadline: deadline)
timer.activate()
这有点麻烦。欢迎提出想法。
【讨论】:
timer.scheduleOneshot(deadline: .now() + 5)后跟timer.activate()。
我通过添加一个触发动作的端点解决了这个问题。然后我有一个 cron 任务触发 curl 命令以在适当的时间到达该端点。
我通过代理通过 nginx 与外界的所有通信来保护这一点,并在我的 nginx 配置中阻止此端点。基于 Swift 的服务器应用程序仅服务于本地主机,它与 curl 命令一起使用,并提供给 nginx,但对于服务器之外的任何内容都被阻止。
【讨论】: