服务器端的计划任务 Swift(Kitura、Vapor、Zewo 等)

Scheduled tasks in Server-Side Swift (Kitura, Vapor, Zewo, etc.)

是否有可能在服务器端 Swift 框架上安排任务,最好是 Kitura?

我需要安排任务;例如,每天凌晨 3 点擦除数据库。

至少在 Kitura 中,我们没有为此提供特殊功能。

您可以考虑使用 Dispatch,它非常适用于每天凌晨 3 点删除数据库的示例。您可以创建一个 DispatchSourceTimer,它在某个时间间隔后分派一些代码一次或重复。

DispatchSourceTimer.scheduleOneshot(deadline: DispatchTimer, leeway: DispatchTimeInterval)
DispatchSourceTimer.scheduleRepeating(deadline: DispatchTime, interval: DispatchTimeInterval, leeway: DispatchTimeInterval)

我通过添加触发操作的端点解决了这个问题。然后我有一个 cron 任务触发 curl 命令在适当的时间到达该端点。

我通过代理所有通过 nginx 与外界的通信来确保这一点,并在我的 nginx 配置中阻止这个端点。基于 Swift 的服务器应用程序仅服务于与 curl 命令一起工作的本地主机,并提供给 nginx,但对于服务器外部的任何内容都被阻止。

我花了一些时间才开始工作,所以这是我得到的:

    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()

这有点麻烦。欢迎提出想法。