简体   繁体   English

Cron 在时隙之间每 5 秒运行一次 PHP 脚本

[英]Cron to run a PHP Script every 5 seconds between time slots

How to run the PHP Script automatically every 5 seconds between the time slots 13:00:00 to 14:00:00 and 16:00:00 to 17:00:00 everyday?如何在每天13:00:00 到 14:00:0016:00:00 到 17:00:00的时间段之间每 5 秒自动运行 PHP 脚本?

PHP Script: PHP 脚本:

<?php
$datetime = date("l jS \of F Y h:i:s A"); 
$apiToken = "1825671537:AAEYexjklpoiyUdEeG8Ml";
$telegram_chatid = '-10012345607';
$message = urlencode($datetime);
                
$telegram_call = file_get_contents("https://api.telegram.org/bot$apiToken/sendMessage?chat_id=$telegram_chatid&parse_mode=markdown&text=$message");
exit();
?>

Use a for loop to run the process 12 times with a 5-second sleep between calls.使用for循环运行进程 12 次,调用之间有 5 秒的sleep Use cron to run this every minute.使用 cron 每分钟运行一次。

* 13  * * *  for i in {1..12}; do (php telegram.php &); sleep 5; done;
* 16  * * *  for i in {1..12}; do (php telegram.php &); sleep 5; done;

The program is detached using & , so the sleep happens directly and not after the script is finished, ensuring it's run every 5 seconds.该程序使用&分离,因此睡眠直接发生,而不是在脚本完成后发生,确保它每 5 秒运行一次。

Well you can't do it with the cron job but you can use the cron job as an initiator.好吧,你不能用 cron 作业来做,但你可以用 cron 作业作为启动器。

This could be a way to solve this issue.这可能是解决此问题的一种方法。 you can run a cron job everyday at 13:00 o'clock.您可以在每天 13:00 点运行一个 cron 作业。

Your script on the other hand should have a loop which sleeps 5 second and goes again through the loop.另一方面,您的脚本应该有一个休眠 5 秒并再次通过循环的循环。 Once you reach 17:00 o'clock it will stop the loop and exit.一旦您到达 17:00 点,它将停止循环并退出。

And there should be another check in the loop, which checks whether you are between the given time eg 13:00-14:00 or 16:00-17:00, if so it will run your script and sleep 5 seconds, if not it will just run the the loop并且应该在循环中进行另一次检查,检查您是否在给定时间之间,例如 13:00-14:00 或 16:00-17:00,如果是,它将运行您的脚本并休眠 5 秒,如果不是它只会运行循环

Another way would be to run a cron job every hour.另一种方法是每小时运行一次 cron 作业。 And in your script you have to check it the hour is the one you want to start doing something.在你的脚本中,你必须检查它是你想要开始做某事的时间。 if so, you just do it like the above loop.如果是这样,您只需像上面的循环一样进行操作。

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

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