Reputation: 951
I have a CRON job which starts every hour and sends messages. If it starts every hour, it sends messages 24 times a day. A user may set a different amount of times a CRON job may start - if he chooses 12 times, cron jobs will work every odd (or even) hour in the following pattern:
where 1 is the hour job worked and 0 is an idle hour. The problem is I dont know how to make a program workout such a pattern for all other amount of times automatically, say for 15 or 17 or somethins else. For such user inputs the pattern would be:
with last hours broken (it will be something like 111 or 100). I tried to divide 15 by 24, add 1, then compare it with the amount of hours since last sending (if 1<1.5 then don`t send, 2>1.5 then send) but I end up with 101010 pattern everytime. And unfortunately I cannot run CRON every minute, it starts only on hourly basis. Thank you.
Upvotes: 1
Views: 100
Reputation: 23379
Based on what you're trying to do, the more frequently the cron job runs, the more accurate your times will be. If it HAS to be every hour, then anything the user selects between 17 and 24 will execute every hour. Therefore it really wouldn't make sense to even provide all those options. If you HAVE to let the user choose a number and execute it evenly throughout the day, you will have to run the cron job more frequently than once er hour.
This example assumes you run the cron job once per minute, ie:
*/1 * * * * <your command>
// How many times per day, get from DB
$userInput = 17;
$SecondsPerDay = 60 * 60 * 24;
$Frequency = (int) ($SecondsPerDay / $userInput) -1;
$midnight = strtotime('today midnight');
// Get an array of times to execute
$executeTimes = array();
for($time=$midnight; $time<=($midnight+$SecondsPerDay); $time+=$Frequency)
$executeTimes[] = date("g:i a", $time);
$currentTime = date("g:i a");
$execute = in_array($currentTime, $executeTimes);
if(!$execute) exit;
// Cron job codes here
Here is an exmaple: https://3v4l.org/0PCXh
note: I think ther's an off-by-one error but you should get the gist from this..
Upvotes: 2
Reputation: 4334
Assuming that all you want is to make a pattern of 0's and 1's where the user picks how often a 1 should appear and they be evenly spaced...
You want 24 total digits. Assume that $n
is the number of hours between events. So, $n=1
means every 1 hour. Then, just use a 1 whenever the hour is evenly divisible by the number of hours between events...
$pattern = '';
for($h=1; $h<=24; $h++)
$pattern.= ($h%$n==0) 1 : 0;
This will give you 111111111111111111111111 if $n=1 (every hour). It will be 0101010101... if $n=2. It will be 001001001001 if $n=3, etc...
Upvotes: 0