我应该如何在 PHP 中创建一次性计划任务?克朗?
我正在创建一个 Web 应用程序,用户可以在其中指定时间和日期来运行 2 个计划任务(一个在开始日期,一个在结束日期)。由于这些只运行一次,我不知道 cron 作业是否合适。
我想到的另一个选择是将所有任务时间保存到数据库并每小时运行一个 cron 作业来检查是否 $usertime == NOW()
等。但我担心工作重叠等等。
有什么想法吗?
其他:许多用户可以创建许多任务,每个任务运行 2 个脚本。
I'm creating a web app where users can specify a time and date to run 2 scheduled tasks (one at the start date and one at the end date). As these are only run once each I didn't know if a cron job would be appropriate.
The other option I thought of would be to save all of the task times to a DB and run a cron job every hour to check if $usertime == NOW()
, etc. But I was worried about jobs overlapping, etc.
Thoughts?
Additional: Many users can create many tasks that run 2 scripts each.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
cron 非常适合定期运行的脚本,但如果您想要一次性(或两次)脚本在特定时间运行,您可以使用 unix 'at' 命令,并且可以直接从 php 执行此操作使用这样的代码:
cron is great for scripts run on a regular basis, but if you want a one-off (or two-off) script to run at a particular time you would use the unix 'at' command, and you can do it directly from php using code like this:
我会这样做,将设置保存在数据库中,并在需要时检查任务是否应该启动。
您可以每分钟运行一次检查/启动 cronjob。只要确保检查代码不是太重(快速退出)即可。每分钟执行几行的数据库查询应该不成问题。
如果“任务”确实很重,您应该考虑使用守护进程而不是调用 php.ini 的 cronjob。这是一个很好的&易于阅读的介绍: 在 PHP 中创建守护进程
编辑:我想当然地认为即使任务仅“每个一次”运行,您也有多个用户,其与“每个一次”的比例为 1:1,因此每个用户都有作业。如果没有,
at
(正如评论所说)看起来值得尝试。I'd do it like that, save settings in a database and check when needed if the task should start.
You could run a checking/initiating cronjob every minute. Just make sure the checking code is not not too heavy (exits quickly). A database query for a couple of rows shouldn't be a problem to execute every minute.
If the "task" is really heavy, you should consider a daemon instead of a cronjob calling php. Here is a good & easy-to-read introduction: Create daemons in PHP
Edit: I took for granted that even if the tasks are only ran "once each", you have multiple users which are 1:1 to the "once each", thereby jobs for each user. If not,
at
(as the comments says) looks worthy of an experiment.无论您选择什么机制(cron/at/daemon),我只会将启动任务放入队列中。与开始任务一起放置的是结束任务。该部分可以将其置于未来,也可以在时间过去后立即启动。这样它们就永远不会重叠。
我也喜欢 PHP/DB 和 cron 选项。看起来更简单并且提供了更大的灵活性 - 如果性能要求的话可以选择多个线程等。
Whatever mechanism you chose (cron/at/daemon) I would only put the start task into the queue. Along with that start task is to place the end task. That part can either place it into the future or it the time has elapsed start it immediately. That way they will never overlap.
I would also favour the PHP/DB and cron option. Seems simpler and gives more flexibility - could chose multiple threads etc if performance dicttates.