How to run a PHP script continuously?

10,448

Solution 1

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

Solution 2

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

Share:
10,448
Shahram Mohseni
Author by

Shahram Mohseni

Updated on June 18, 2022

Comments

  • Shahram Mohseni
    Shahram Mohseni about 2 years

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

  • Ima
    Ima over 7 years
    Please do a search. Its available all over internet.
  • Ima
    Ima over 7 years
  • Ima
    Ima over 7 years
    What is your hosting partner ?
  • Shahram Mohseni
    Shahram Mohseni over 7 years
    as i understood if just one time i visit the page, then it will run like it's open .. and very important does it support jquery at background mode >
  • Peter
    Peter over 7 years
    No, it cannot support jquery in the background since jQuery is a client side language and cannot be executed on the server.
  • Shahram Mohseni
    Shahram Mohseni over 7 years
    sorry i am weak at words .. partner in host ? if it's web hosting so it is bertina.us if u mean the sms gateway it is www.sms.ir
  • Walf
    Walf over 7 years
    Long-running PHP scripts are prone to failure, and need ways to automatically recover from being killed or hangs. The best way to achieve OP's goal is to use one cron job to poll a script every 1, 5, or however many minutes. That script should check a file (or db value) for a date + time. If the date + time is ≤ the current time, it should look through the full queue of tasks and do any that are ready. That date + time value should be updated with the next soonest from the queue whenever tasks are added/removed/finished. This is more efficient than searching the full queue every time.
  • Shahram Mohseni
    Shahram Mohseni over 7 years
    Peter i advanced my question through your answer , will u please check it bellow the main question in top ..
  • Peter
    Peter over 7 years
    You can thank me by accepting my answer by clicking on the button to the left of my answer.