This question already has answers here:
Schedule and execute a PHP script automatically
(7 answers)
Closed 9 years ago.
I am developing a web app which requires events. The user creates an event at a specific time, and I need a script to be executed and activate the event at the exact time, so the event can start.
Any ideas on how I can do this? I googled and searched through stack overflow, but all I encountered was multiple execution at specific time. What I need is execution at automatically set time.
Hope you help me, I'm desperate.
You have 3 options. My recommendation: Use cron if you can, user driven if you have to, and daemon as a last resort.
(1) cron (as mentioned in comments)
cron is a scheduler for linux systems that will run a command line job on your system. You log into your server over ssh, type crontab -e, and add a line like this:
4 5 * * * php /path/to/my/script.php
This would run the script at 5:04 a.m. every day.
<?php
// /path/to/my/script.php
// Do something
Some hosting services allow entering cron jobs with a GUI. There are also external cron services, that will call a URL for you at specific times.
(2) daemon
This is the most advanced option and also the least reliable: You run a command line script that contains an infinite loop. The script then periodically checks state and responds to it. Because it is likely to crash after months of running, you have to have a second script to restart it in case it does. This is a lot of work, but it is the most flexible approach.
<?php
while (1) {
// fetch $last_exec_timestamp from database
if ($last_exec_timestamp < time() + 86400) {
// set last_exec_timestamp to now in database
// do something
}
sleep(5);
}
3. user driven
If you have a decent amount of traffic on your site, you can simply include a the job this in your page footer, when there is no more output. Make sure this code is fast, or an unlucky user will be waiting for it.
<?php
// fetch $last_exec_timestamp from database
if ($last_exec_timestamp < time() + 86400) {
// set last_exec_timestamp to now in database
// do something
}
There are also to more fancy approaches of "user driven" that I haven't personally tested in another stack overflow question.
What u are looking for is CRON JOBS
http://net.tutsplus.com/tutorials/php/managing-cron-jobs-with-php-2/
Related
Trying to make a dice-roll function in my telegram bot.
How it works right now:
When a user sends "roll" bot replies with sendDice method and sends another message with result like "you rolled 5, you won and blah-blah .."
> how it looks <
The problem is — the second message should not appear instantly, ideally after dice-roll animation is finished.
My first and obvious try on that was to add "sleep(3)" before sending the second message, and it worked fine, until I realized it completely delays the execution of my script for those 3 seconds. (if two users rolled at the same time, one of the users has to wait until another guy's roll will be finished). So it's not cool
What can I use? :c
The easiest option is to add the "task" to the "queue". The queue can be a table in the database with timestamps and chat id, when and to whom to send a message. Start another process, for example, which is started by cron, and it works for one minute. During that minute, he goes to the database and checks to see if there is something that needs to be sent now.
Crontab config
Open crontab
sudo crontab -e
Add next string
* * * * * php /path/to/cron.php >> /path/to/log/file/for/debug.log 2>&1
Cron run your script every 1 minute.
Cron.php "live" 60 second
cron.php:
$now = time();
$expectedTime = $now + 60;
while (true) {
Worker::run();
if ($expectedTime < time()) {
die(0);
}
}
Where Worker::run() your method, which get records from db, check timestamp and send message
From Wikipedia:
In computing, [..] fork is an operation whereby a process creates a
copy of itself.
When your PHP script runs, you can create multiple processes that interact with each other. Those processes run concurrently and asynchronous. This way you can have one process waiting to send the message, while the rest of the script continues to run.
Instead of starting another process, you could also start another thread. The technical difference between the two is explained here:
Forking vs Threading
PHP offers Process Control Extensions for both forking and threading. You might want to check out the example in the PHP documentation for pcntl_fork().
Depending on your needs, you might want to use a framework designed to handle concurrency throughout your application. If that is the case, I would recommend amphp.
This question already has answers here:
How to set up a cron job to run an executable every hour?
(7 answers)
Closed 3 years ago.
I want to populate a hostoric database installed on a server. To do that I have to send multiple (curl)http requests on an endpoint changing the value of a certain field of a certain entity, also saved on a diffferent database. The problem is that I need to change the value of the field every hour for many days. I get it that people use cron jobs for this kind of task, but I need to know firstly in what language should I write the script preferrably(php, python, etc-with php being my personal preferred choice), or it does not simply matter and the important thing is to execute it via cron? Also what would the syntax for cron be in my scenario where I need to change the value every hour for say seven days?
Hi there are a lot of possibility to do cronjob, depends of your infrastructure. For example:
in a web-hosting with cpanel/plesk you can call a script (php for example)
you can also do cron by using user a starter, e.g. by creating a table on db with last execution on every user you can check the last execution and comparing it with actual time you can decide if start or not a scripts
you can create a crontab for your server in caso of managed server or vps (e.g. https://crontab-generator.org/)
you can use an online cron service. e.g. https://www.easycron.com/
and so on...
put in simple words:
i am writing php scripts which send and receive sms,
scripts will calculate to send users campaign SMS every week based on each user registration date, for example every monday 10 AM send sms to mr. A and every friday at 7 pm sends sms to miss B..
and php scripts will take care of everything needed ..
problem : obviously a very funny way is to have someone refresh the main page of my application every some seconds or so to be able to continue to calculate and understand what and when to do jobs, or have the main page always open on my computer so javascripts and jquery will handle the rest!
My Question : how can i have my php program or scripts to be something like awake without need to someone refreshes or have open the main page? by awake i mean like it senses the next schadule and executes it and so on ..
some raw ideas to answer : perhaps i could call the main page using ajax or curl every 10 seconds .. but i don't know how to awake ajax or curl in first place ..
i see some internet posts suggest something like command line either in linux unix or windows .. but i usually access the host not the command line is it right ? or command line is something in host and i don't know it, if so please help me ..
important example : there are php wp plugins like total cache and supper cache which seem to be always on and awake of schedules without need of somebody refreshing a page ..
please give answers all in php and php families if possible, i don't know unix or those kind of programmings at all ..
------- accourding to answers made some progress to question ..
now i have this bellow script :
ignore_user_abort(true);
set_time_limit(0);
$data = file_get_contents('filename.txt');
$data = $data+1;
file_put_contents('filename.txt', $data);
$page = $_SERVER['PHP_SELF'];
$sec = "4";
header("Refresh: $sec; url=$page");
it works! even when i restart the local host . main problem is now when i closed the main page it stopped incrementing in filename.txt and when reoppend the page two instance where running the increment continued so :
should'nt it continue to increment even when i close the page ?
and how i stop it ?
and is it normal to have more than one instance of the page run in background?
finally : according to instructions on this page it's best i create a starter or reload page then use commands to initiate this reload page for example every 1 minute and then write PHPs like normal ..
last not least : how to stop this background script ? for update or maintenance ..
For this particular issue cron jobs have been invented. Cron jobs are timed jobs that can for example execute a PHP script.
You could set up a cron job to check which user should receive his/her sms every hour. Depending on your operating system you can set up these cron jobs. For linux distrubutions there are tons of guides on how to set this up.
From Wikipedia:
The software utility Cron is a time-based job scheduler in Unix-like computer operating systems. People who set up and maintain software environments use cron to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals. It typically automates system maintenance or administration—though its general-purpose nature makes it useful for things like downloading files from the Internet and downloading email at regular intervals. The origin of the name cron is from the Greek word for time, χρόνος (chronos). (Ken Thompson, author of cron, has confirmed this in a private communication with Brian Kernighan.)
I have added a resource explaining how to use cron jobs.
An alternative method is to keep a PHP script running in the background:
// Keep executing even if you close your browser
ignore_user_abort(true);
// Execute for an unlimited timespan
set_time_limit(0);
// Loop infinitely
// If you create a file called stop.txt,
// The script will stop executing
while (!file_exists('stop.txt')) {
// Retrieve user data and sens sms messages
// Wait for an hour
sleep(3600);
}
Update
ignore_user_abort(true);
set_time_limit(0);
$data = file_get_contents('filename.txt');
while (!file_exists('stop.txt')) {
// Add 1 to $data
$data = $data+1;
// Update file
file_put_contents('filename.txt', $data);
// Wait 4 seconds
sleep(4);
}
To stop executing create a file called stop.txt
Resources
About Cron jobs
You can create cron jobs in almost all servers without accessing command prompt.
Cron job can be used to initialize php scripts in cli at specified intervals lik every minute, every hour etc
Hello fellow programmers! :)
I want to be able to set up some php script to be run after some events, triggered by user. Let's say, user creates a forum thread, that should be closed after 48 hours automatically. It is equivalent to an update to MySQL row:
UPDATE threads SET closed = '1' WHERE threads.id = 'x'.
Hence, this problem should not necessarily be solved exclusively with php.
This kind of questions pop up from time to time, but everything I found was to set up a cron job to run every 'x' amount of time, that checks if the time has come to close the thread. The problem is, that running this checks often cause higher system load than if you schedule a script to be run once at a given time. Not to forget, that there could be hundreds or even thousands of threads, each with it's own time to be closed. We can avoid checking every single thread by creating some sort of queue, for instance in MySQL, so the script selects from the DB entries with "time_to_close < NOW()" and closes these. Another drawback is, that I would like the thread to be closed exactly after 48 hours. In that case the script should be run every second and should take very little time to be executed completely.
Alternatively to cron job I think following method can also be useful:
check at every access to the Thread if it should be closed. This also causes higher load, especially if the thread is accessed very often.
So is there any efficient way to schedule a (php) script run depending on the time of a specific event? While writing this question I stumbled upon MySQL event scheduler. Together with procedures, that can provide additional flow control (close thread only if there was no activity since 48 hours) I think my idea can be implemented. I am not familiar with these functions of MySQL, so I would appreciate any help on this topic.
With best regards,
system__failure.
I know a lot of websites compensate for this kind of behavior by doing this on a per user request basis. The overhead is not that bad and your records are always displaying correctly (unless you have a design problem.) This also works because most hosts don't give you cron access. It is very rare you will need to schedule a job in php. There are a few exceptions like report generations every hour. But trying to catch user actions with cron is not a good idea.
I have questions stored in my database. I want to regularly post one question on my website from the database at a 24 hr interval automatically. Is there a way I can do that ?
You can do this with steps:
Create normal PHP-script which will post your questions.
Schedule your script with standard OS scheduler. It is cron for *nix (Win-versions exist too) or AT for Windows. To define certain interval - you should read scheduler's manual (for cron format is provided here)
Example (cron)
0 2 * * * /usr/bin/php /path/to/insert/script.php
-in this case every day at 02:00 AM cron will try to execute command /usr/bin/php /path/to/insert/script.php - i.e. if your script.php will extract your question from DB and post it - that will do the stuff.
Yes you can do it by using Cron job . Set time interval and your file script location. It will automatically hit your script on that time interval.
Here is good tutorial : http://docs.phplist.com/SetupCronJob.html
Providing you could create a PHP script to select a different question each time, all you'd need to do would be to set up a cron to run the PHP script every 24 hours. You can find more info on cron here.
You should look into MySQL date functions.
A contrived example would be using CURDATE():
SELECT * FROM questions WHERE publish_date = CURDATE()
Storing the publish_date will mean you can dynamically load the question when that date arrives.
The only way to do it correctly is to use cron jobs. You should take a look at the administration panel of your hosting service.
Write a script that will post one question on your website everyday and set a cron job to run that script once a day and you are done.
How to set a cron job , ask you hosting service provider , most of the hosts have this feature in cpanel
Yes, you can. I will shortly outline the two most common solutions. The difficulty rises that PHP is not an always running program, but is a language executed on request and then shutdown on completion.
Have some sort of init.php file on your webserver which is being included on every page. That script will check whether the time has passed since last question, and push a new question.
On the other hand, you can add a cronjob which will execute your php script pushing the question. This solution is more robust, but requires access to a webserver you might not have.
Create a php file put the code to fetch question form your database
then set cronjob to excecute the file on perticular time or also
you can execute file by including it your login or any other page which
lods first by including that php file file so that when first user logs in
it will execute.
Steps
Create a PHP script to select and post a particular question randomly.
In your main php script write an AJAX method(which will load the PHP script) which can be called using setInterval() using the following syntax-
setInterval("AJAX_fun()", 24*3600*1000);
This statement will call the AJAX function in a periodic interval of 24hrs. For that you must know AJAX. I mean what should be the body of the AJAX to load the PHP script that you must have an idea of.
Another alternative
You can simply reload the page using javascript setInterval() function
i.e. <script>setInterval("window.location.reload()", 24*3600*1000);</script> and before that you have to select a question from the database randomly using a PHP logic.