在特定条件下停止执行cron作业

I have a DB with 2 tables:

subscribers:
 _____________________________
|  id    |  name  |   email   |
|________|________|___________|
|  1     |  John  |   e@m.com |
|  ..    |   ..   |     ..    |
|  5000  |  Mark  |   c@b.com |
|________|________|___________|
last_id:
 _______
|  id   |
|_______|
| NULL  |
|_______|

Every day I run a cron job to send all the emails at once, But The script is timing out after 100 sec.

So instead I'm thinking of sending about 200 emails per time:

/* Get the id from last time is script was executed */
$last_id = "SELECT `id` FROM `last_id`";

/* Select the next 200 subscribers starting from the last id */
$query= "SELECT * FROM `subscribers` WHERE `id` > ". $last_id . " LIMIT 200";

/* Send 200 emails */
..

/* Get the last id of these 200 subscribers */
$last = ;

/* Update the value of `id` in `last_id` table */
$query= "UPDATE `last_id` SET `id` = ". $last;

The cron job runs this script every 10 minutes, But after sending all the emails the script would be executed over and over without sending any emails.

So how to stop executing this cron job after all the emails are sent, When last_id = 5000 and start it again the next day?

douxiong5972
douxiong5972 那么您建议作为替代方案?
大约一年之前 回复
douguaidian8021
douguaidian8021 “那么如何在发送所有电子邮件后停止执行此cron作业,并在第二天再次启动它?”您在这里尝试优化的是什么?不要浪费时间思考/编程优化cronjob与空表选择哪个开始快速点亮..思考/编程的小时数不能证明性能增益可能几毫秒。当PHP看到表为空时,脚本可以使用return或exit(0)。
大约一年之前 回复
drsb77336
drsb77336 是的,您也可以在sleep()之前取消设置()内存消耗变量,一旦到达表的末尾,您可以在第二天将last_id重置为0
大约一年之前 回复
down00111
down00111 暂停10分钟,你的意思是使用睡眠(600)?
大约一年之前 回复
dsp15140275697
dsp15140275697 你可以直接在你的php脚本中“构建”10分钟的暂停:每天运行一次,每次迭代发送200封邮件,然后等待10分钟。或者,您可以检查是否到达表的末尾并将状态放在数据库中的某个位置(例如last_id=-1)然后让另一个cron每天将其重置为0
大约一年之前 回复

1个回答

We had an exercise like this at school once, we sorted it by adding a 'send date' column to the subscriber table. You select with a limit X and a date < then 'now', upon sending you update the records of these subscribers with the 'now' date.

The query wont select anything if all are send. so the cron will run but doesn't do anything.

And the next day, it will start with again as the select will return the 'unsend' records.

And if you don't want to use the dates, you can use a bool or tinyint, select where 'send' is 0 and set them to 1 after sending. And have another cron update all the records back to 0 run once daily/or whatever increment you want to send these emails.

doutang9037
doutang9037 每隔X分钟。
大约一年之前 回复
douxiangbiao1899
douxiangbiao1899 每隔x分钟或每天执行一次cron工作?
大约一年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐