How to run a PHP script continuously? How to run a PHP script continuously? wordpress wordpress

How to run a PHP script continuously?


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 browserignore_user_abort(true);// Execute for an unlimited timespanset_time_limit(0);// Loop infinitely// If you create a file called stop.txt,// The script will stop executingwhile (!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


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