Cron to run a PHP Script every 5 seconds between time slots - php

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.

Related

PHP: issuing a cron job once every 24hrs from initial date

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

Execute a php script everyday at different time

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).

Running a script for certain days

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

Run code only between certain hours

I am trying to run a certain batch of code only during certain hours of the day. I want to run this code only after 8:00am and before 10:00 pm.
This code is included in the footer of my site, but it doesn't seem to be working, it is still running the code through these hours. (my server is in the same time zone as I am):
if(date("Hi") < 2200 && date("Hi") > 0800){
// Run Code
}
How can I run the code only between the specific times?
if(date("Hi") < 2200 && date("Hi") > 800){
// Run Code
}
Try with strtotime function and relative formats:
if ( time() > strtotime( '08:00AM' ) && time() < strtotime( '10:00PM' ) ) {
// run code
}
Like Ryan said up in the comments - You need to set this up as a cron job.
http://www.thegeekstuff.com/2009/06/15-practical-crontab-examples/
to see your crons:
crontab -l
edit the crontab
crontab -e
an example cron that runs at 8am daily
00 08 * * * php path/to/script.php
The problem with setting it up the way you are attempting to is that every single request to your site is going to set off the event again (a possibility of mucking up the transactions)
just use "G" to get hours without leading 0
$time = date("Gi");
if(800 <= $time && $time <= 2200){
// Run Code
}

random delay timer in PHP

I want to put a php daemon to sleep (with System_Daemon::iterate())
so it runs max 20 times randomly spread over an hour. maybe a min distance would be smart so it doesn't run 20 times in the first half hour and 0 times in the second half.
i'm kinda stuck here and don't know how to start with this one, any help is very apreciated!
You may use cron jobs, to set the script to run ever so often.
http://net.tutsplus.com/tutorials/php/managing-cron-jobs-with-php-2/
... Crontab:
0 9 * * * /path/to/bashscript
and in /path/to/bashscript:
#!/bin/bash
maxdelay=$((1*60)) # every hour, converted to minutes
for ((i=1; i<=20; i++)); do
delay=$(($RANDOM%maxdelay)) # pick an independent random delay, 20 times
(sleep $((delay*60)); /path/to/phpscript.php) & # background a subshell, then run the php script
done
i came up with one possible solution, i didnt try it out yet, so it main contain syntax or logic errors. because it is running as a daemon there is a never ending loop around it.
// 3600 seconds or one hour
$timeframe=3600;
// run max 20 times in $timeframe
$runtimes=20;
// minimum delay between two executions
$mindelay=60;
// maxium delay between two executions
$maxdelay=240;
if ($cnt % $runtimes != 0) {
$delay = rand($mindelay,$maxdelay);
System_Daemon::iterate($delay);
$sum += $delay;
$cnt++;
} else {
//final delay till the $timeframe
if ($sum < $timeframe) {
System_Daemon::iterate($timeframe - $sum);
}
$sum=0;
}
its not perfect and u waste some time but i guess its going to fullfill the job.
any comments?

Categories