如何每分钟多次运行 Cronjobs?

编程入门 行业动态 更新时间:2024-10-25 18:23:55
本文介绍了如何每分钟多次运行 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?

本文发布于:2023-06-07 15:30:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/568638.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:每分钟   Cronjobs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!