如何每分钟多次运行 Cronjobs? [英] How to run Cronjobs more often than once per minute?

查看:33
本文介绍了如何每分钟多次运行 Cronjobs?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个电子邮件队列数据库表.我将把我的 PHP 应用程序需要发送的所有电子邮件插入到这个表中.

I created a Email-Queue database table. I will insert all Emails my PHP application needs to send into this table.

另一个 PHP 脚本将查找所有未发送的电子邮件并发送它们.

Another PHP script will then look for all unsent Emails and sends them.

我使用 cronjobs 运行此脚本.不幸的是,cronjobs 每分钟最多只能运行一次.所以在最坏的情况下,用户必须等待一分钟,直到他的电子邮件真正被发送.

I run this script using cronjobs. Unfortunately cronjobs can run only at a maximum of once per minute. So in the worst-case a user has to wait one minute until his Email is really going to be sent.

我目前的解决方法是使用额外的 sleep 参数调用脚本并复制 cronjobs.

My current idea for a workaround is calling the script with an addtional sleep parameter and duplicating the cronjobs.

示例:

* * * * * curl emails.php?sleep=0 >/dev/null 2>&1
* * * * * curl emails.php?sleep=10 >/dev/null 2>&1
* * * * * curl emails.php?sleep=20 >/dev/null 2>&1
* * * * * curl emails.php?sleep=30 >/dev/null 2>&1
* * * * * curl emails.php?sleep=40 >/dev/null 2>&1
* * * * * curl emails.php?sleep=50 >/dev/null 2>&1

在上面的示例中,脚本将每 10 秒运行一次.emails.php 脚本的第一行是:

In the above example the script would run every 10 seconds. The first line of the emails.php Script would be:

sleep($_REQUEST['sleep']);

推荐答案

对于初学者,我建议使用 PHP 的命令行版本,而不是使用 curl 来调用脚本.然后,您可以创建一个具有合理生命周期的 PHP 脚本,该脚本不受必须在给定时间段内输出响应的限制.

For starters, I'd recommend using the command line version of PHP rather than using curl to call a script. You can then create a PHP script with a sensible lifetime that isn't constrained by having to output a response within a given time period.

因此,您可以在 PHP 脚本中简单地睡眠/检查电子邮件/传输/睡眠等,而不是不必要地使用 cron.

As such, you can then simply sleep/check for emails/transmit/sleep, etc. within the PHP script rather than needlessly using cron.

此外,我会注意确保多个 PHP 脚本不会同时在数据库表上运行,无论是使用 pid 文件还是数据库设置方法(如果给定的文件/设置存在/已设置),中止处理)或通过在开始周期的检查电子邮件"部分之前检查脚本运行的时间来合理地计时 cron 作业并限制脚本的最大处理时间.

Additionally, I'd take care to ensure that multiple PHP scripts aren't operating on the database table at the same time, either by using a pid file or database setting approach (if a given file/setting exists/is set, abort processing) or by sensibly timing the cron job and limiting the maximum processing time of the script by checking how long it's been running for prior to beginning the "check for emails" portion of the cycle.

这篇关于如何每分钟多次运行 Cronjobs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆