automatically schedule a php script execution at s

2019-02-20 05:33发布

This question already has an answer here:

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.

2条回答
beautiful°
2楼-- · 2019-02-20 06:04
Melony?
3楼-- · 2019-02-20 06:12

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.

查看更多
登录 后发表回答