I'm having a little confusion with crontab interval format. The point is that i want to get intervals from human-readable strings like "20 minutes", "16 hours and 30 minutes". This is done by PHP DateTime already. But what I need is passing crontab-valid string as exec(sprintf('echo "%s %s %s * * %s" | crontab', $minute, $hour, $day, $command));
. Anyhow, here is sample PHP script
<?php
function getCrontabInterval($timestring)
{
$interval = DateInterval::createFromDateString($timestring);
$minute = $interval->i > 0 ? "*/{$interval->i}" : '*';
$hour = $interval->h > 0 ? "*/{$interval->h}" : '*';
$day = $interval->d > 0 ? "*/{$interval->d}" : '*';
$crontab = sprintf('echo "%s %s %s * * %s" | crontab', $minute, $hour, $day, '%command%');
echo "Days:\t\t", $interval->d, "\n",
"Hours:\t\t", $interval->h, "\n",
开发者_如何学运维 "Minutes:\t", $interval->i, "\n",
"COMMAND:\t", $crontab, "\n";
}
getCrontabInterval($_SERVER['argv'][1]);
And its output:
serge@serge-laptop:~/www/bin$ php periodical.php '2 hours 25 minutes'
Days: 0
Hours: 2
Minutes: 25
COMMAND: echo "*/25 */2 * * * %command%" | crontab
So, will the "*/25 */2 * * *" cron value match running command EACH 2 hours 25 minutes? Or it should be something like "0/25 0/2 * * *"? It was not clear for me from manpages. And how to act with days?
UPD: Under each "2 hours 25 minutes" i mean running at 0:00, 2:25, 4:50, 7:15 and etc
SOLUTION: used two-component value for intervals with some manual recommendation to use values like 20 minutes, 3 hours, 4 days and etc.
*/25 */2 * * *
means at 0:00, 0:25, 0:50, 2:00, 2:25, 2:50, 4:00, 4:25, 4:50 etc...
25 */2 * * *
means 0:25, 2:25, 4:25, 6:25, etc...
0/25 0/2 * * *
means 0:25 only
EDIT - After your update
To my knowledge there is no way to do it with a single line in a crontab. The mechanism for specifying at what time your cron job runs is not meant for this kind of complexity. You can however have 9 or 10 entries in your crontab with different times to the same script if you really need that 2h25 functionality
String "*/25 */2 * * *" will runs command each 2 hours EACH 25 minutes
String "25 */2 * * *" will runs command each 2 hours 25 minutes
精彩评论