简体   繁体   English

我们可以通过PHP脚本配置cron作业的时间间隔吗?

[英]Can we configure cron job's time interval through PHP script?

Can we configure cron job's time interval through PHP script, so that the time interval should not be set manually, but through a PHP script, whether it takes time interval from Database or fixed (but from within the PHP code). 我们是否可以通过PHP脚本配置cron作业的时间间隔,以使该时间间隔不应该手动设置,而是通过PHP脚本设置,无论它是来自数据库还是固定(但来自PHP代码)都需要时间间隔。
Thanks in advance 提前致谢

I think it is much better to let your application control the frequency of events instead of the cronjob. 我认为让您的应用程序控制事件的频率而不是cronjob更好。 Let the cronjob run a certain action of your application every minute. 让cronjob每分钟运行您的应用程序的特定操作。 The action then for example checks a database table named cronjobs and runs the jobs marked for running by either a frequency number or a timestamp. 然后,该操作例如检查名为cronjobs的数据库表,并运行按频率编号或时间戳标记为正在运行的作业。

If you do it like this, you can add new jobs programmatically from everywhere, eg via an cronjob interface. 如果这样做,您可以从任何地方以编程方式添加新作业,例如通过cronjob界面。 The solution is easier to maintain, to test and to document . 该解决方案更易于维护,测试和记录

There are two ways. 有两种方法。 Either, re-create the crontab on every change of the desired value or have the cron job fire regularly, eg every minute, and test the starting condition from within the script. 要么在所需值的每次更改上重新创建crontab,要么定期(例如每分钟)启动cron作业,然后从脚本中测试启动条件。

如果有足够的服务器特权,则应该能够通过使用System ()从PHP脚本进行系统级调用来实现。

The best to do this, would probably be by writing a PHP script that is capable of creating a crontab -file (and running your script with sufficient privileges to do this). 最好的方法可能是编写一个能够创建crontab -file的PHP脚本(并以足够的权限运行脚本来执行此操作)。

This site offers a pretty good tutorial. 这个站点提供了一个很好的教程。

However, dependency on cron will make your code dependant on platforms that support cron . 但是,对cron依赖将使您的代码依赖于支持cron平台。 Thus another solution would be to implement the timed-execution-logic in PHP itself (ie loop the code, and check the time yourself). 因此,另一个解决方案是在PHP本身中实现timed-execution-logic(即,执行代码,然后自己检查时间)。

You could combine the two solutions above, by creating a Scheduler -interface that you can give a script, and it will make sure it's executed at the appropriate times. 您可以通过创建一个Scheduler来组合上面的两个解决方案,该接口可以提供一个脚本,并且可以确保在适当的时间执行该脚本。 This way you can implement it using cron on linux, but in another way on Windows: 这样,您可以在Linux上使用cron来实现它,但是在Windows上以另一种方式来实现:

interface Scheduler {
  function schedule($script);
}
class CronScheduler {
  function schedule($script) {
    append_cronjob($script);
  }
}

Though, I might be overdoing it here. 虽然,我可能在这里过分了。

If you want to do this I would suggest you to use Message Queue Beanstalkd instead. 如果要执行此操作,建议您改用Message Queue Beanstalkd It can do delayed put programmatic and is very fast. 它可以以编程方式执行延迟放置,并且速度非常快。 I advice you to use pheanstalk to talk the Beanstalkd. 我建议您使用pheanstalk交谈Beanstalkd。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM