I have a script PHP which do requests on MYSQL server, and I want to execute itself once a day!
The first time, I execute the script myself.
And I want the script, at the end of the execution, choose a random time in the day, between 8:30AM and 7:30PM, and reexecute itself automatically the day after, at this time. Is it possible?
To choose a time randomly I have coded like this:
$tomorrow = new DateTime(date('Y-m-d H:m:s', time()+86400));
$tomorrow1 = $tomorrow -> setTime(8,30,0);
$tomorrow2 = $tomorrow -> setTime(19,30,0);
$min_time = strtotime($tomorrow1->format('Y-m-d H:m:s'));
$max_time = strtotime($tomorrow2->format('Y-m-d H:m:s'));
$rand_time = rand($min_time, $max_time);
But then I don't know how to do an automatic execution for the script at this time. Maybe I can pause like this:
sleep ($rand_time - time());
But I don't know how to reexecute the script after that. And I don't think sleep is the best solution. Do you if there is a way and how to do this?
Allright, I can use cron, but the issue still remains: I need to be able to modify the task scheduler for the day after everyday by the php file itself!
The approach taken by e.g. APT::Periodic is to start the job at a fixed time (in your case 08:30) and sleep for a random period of time as the first command in your job (in your case for $(($RANDOM % 39600)) seconds, assuming your shell is Bash).
This avoids the need to write anything to the crontab.
I don't know PHP, but I think it would look something like:
#/usr/bin/php
// Wait 0-11 hours before starting (invoked by cron at 0830)
sleep(rand(0, 39600));
// It's now a time between 0830 and 1930
// rest of your code here
and your crontab would be simply
30 8 * * * /path/to/my/script
Alternatively, don't sleep at all in your script, but do the sleep in the crontab command:
SHELL=/bin/bash
30 8 * * * sleep $(($RANDOM % 39600)) && /path/to/my/script
This may be preferable if you ever need to execute the script by hand (and not want to wait up to 11h for it to start).
Related
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?
PHP Script :
<?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. Use cron to run this every minute.
* 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.
Well you can't do it with the cron job but you can use the cron job as an initiator.
This could be a way to solve this issue. you can run a cron job everyday at 13:00 o'clock.
Your script on the other hand should have a loop which sleeps 5 second and goes again through the loop. Once you reach 17:00 o'clock it will stop the loop and exit.
And there should be another check in the loop, which checks whether you are between the given time e.g. 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
Another way would be to run a cron job every hour.
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.
I have created two functions in a separate php file and want them to run over and over.
After function A completes, I want it to compare the current time, relative to the last time function B ran, and if more than 24hrs has elapsed (or whatever value I set it to), it runs function B, resets the next time for when it should be trigger to run, and continues to run function A. They need to run separately and not parallel since values altered in function A will affect function B and thus need to be separate. The ideal scenario is I have a config.php file where I set the time delay (in hours), but I can sort that out later!
I am stumped on how to get this while(true){} loop organized... any ideas?
Regardless of whether you end up doing it this way (because I think the comments about cron make some good points, and there are some other issues you may run into with a continuously running PHP script like this) here's a basic logic for executing the alternate function based on a defined delay.
// define the delay and initialize the timestamp
$delay = 86400; // 24 hours, for example
$last_time = time();
while (true) {
functionA();
// the next time functionB should execute is the timestamp for the last run + the delay
if (time() > $last_time + $delay) {
functionB();
$last_time = time(); // reset the timestamp
}
}
Would something of this nature be similar to what you're looking for?
while ($time > 13 && $time < 21)
You could have flags involved in each function as well. If a boolean flag is fired and is = 1, then continue on?
I was wondering if I could get some help.
I have a cronjob that is run every 5 mins.
I also have a number of entries in my DB with a 'start date' formatted like
'yyyy-mm-dd HH:mm:ss'
What I want to do is run a specific command for each entry 24 hrs after the start date.
So for instance, if an entry has a start date of 2016-11-18 12:08:44, I want to run a command on that entry at 2016-11-19 12:08:44 ... Because the cron only runs every 5 mins, I don't expect to be exactly spot on 24hrs, but as close (5 mins each way) as possible.
Is there any chance someone could give me an example of how I could achieve this in PHP?
Much appreciated.
You should do the job like this :
Add a column "desired launch date" in the DB (Nullable).
Write a php script what calculate all 'desired launch date' from 'start_date' (and update the DB with calculed date).
Add block on this PHP script that initialize current datetime and compare with 'desired launch date' with an interval of 10 minutes.
EDIT :
Here a piece of source code, not tested !
$datetime = new \Datetime();
$timestamp = $datetime->getTimestamp();
$datetime_desired_launch = new \Datetime($your_formatted_datetime_from_db);
$desired_timestamp = $datetime_desired_launch->getTimestamp();
// I have manipulate timestamp for more efficiency
$launch_min_interval = $desired_timestamp - 5 * 3600; // - 5 minutes
$launch_max_interval = $desired_timestamp + 5 * 3600; // + 5 minutes
if ($timestamp >= $launch_min_interval && $timestamp <= $launch_max_interval) {
// Here launch action...
}
Be careful of timezones !
Hope this help !
You can use crontab to lance a script each 5 min
In this script you can check for date and lance the others scripts
I am developing a php script, which should run a shell script for every 20 mins for one 10 days.
I did explored the option of crontab but, crontab gives duration or specific time of every day.
It does not have option for running script every 20 mins for 10 days continuously.
If anybody has better option kindly, suggest.
Thanks !
Put this in your crontab:
*/20 * * * * bash /path/to/your/script.sh
Then remove it after 10 days.
Better yet, have your script check the current date and send you an email when it's 10 days from now to remind you to remove it.
You could also just have the script remove the line from the crontab (or just remove the crontab file if it's only got this one line) after 10 days.
I agree with everyone else use crontab, then on your php file you could do this:
if(time() > strtotime('2013-08-01 00:00:00 +10 days')) {
die();
}
Look at the at command, which will run the command specified at the specified time. Note you will have to do your own calculation to determine each run time, and you'll wind up with a seed script like this:
$ for i in {0..720}; do echo 'php the-command.php' | at now + $(($i * 20)) minutes; done
I am currently writing a online game. Now I have to check if an event happen (checking timestamp in database) and depending on that execute some actions. I have to check for an event every second.
I wanted to use a cronjob but with cron you can run a script only every minute.
My idea was to use cron and loop 60 times in my php script. But I think this isn't the best solution.
So whats the best way to run a script every second?
I searched for a better solution but it seems that my first idea, with clean code, is the best solution.
This is my current code:
<?php
set_time_limit(60);
$start = time();
for ($i = 0; $i < 59; ++$i) {
// Do whatever you want here
time_sleep_until($start + $i + 1);
}
?>
Why not modify the script so that it just repeats the code every second? This will reduce the parsing overhead and be less complicated.
You should probably run the script once, and use a loop with delay to accomplish your desired timing.
The side benefit is that this is more efficient, and you would only have to open resources (ie, databases) once.
You shouldn't want this :P. No host will accept your cronjob is running every second every minute?
You can save the time it runned in a database, and the next time you run it calculate the time between both runs and do the calculations you want. every second is a very bad idea.
$total_time = 0;
$start_time = microtime(true);
while($total_time < 60)
{
//DoSomethingHere;
echo $total_time."\n";
//sleep(5);
$total_time = microtime(true) - $start_time ;
}
add this in crontab to run every minute.