PHP scheduling a task on webhosting without SSH/Console

我的未来我决定 提交于 2019-12-11 17:38:27

问题


I have a php website that has a script that executes an update for my database with data from an external API. The script itself works perfectly fine but i need to time it so that it executes it every monday at 2:30 AM. I am using a webhosting where SSH is not available neither is any form of command execution such as exec() or passthru(). I've also looked at CRON jobs but i can't use that either because i have no access to a console.

An other option i found was using threads with phthreads. But it seemed that i need an extra libary (PECL) to use it, but again because i can't use any console i can't install that dependency.

So another solution i came up with myself is the idea of stealing a request of the first user that visits the website. I know it's not a beautiful solution that's why i want to ask if there are some other options for me where i can schedule a task. Or is stealing the request the only option here? Or did i make a mistake in my assumptions?

Also a VPS is no option for me.

Sorry for my bad english, it's not my native language.


回答1:


One way to do it is to let your visitors trigger the update.

  • The advantage to this is you are not exposing your updating script to the world.
  • The disadvantage is that your database will not be updated until the visit of your first user after 2:30 am on Mondays, and that first user will have to wait for the database to be updated.

Add this to your script:

/**
 * Checks if the database's last update was before 
 * Monday at 02:30
 *
 * @param \DateTime Time of last update.  Must be converted to DateTime object
 * @return boolean
 */
function databaseIsOutOfDate(DateTime $createDate) {

  // find the last Monday at 2:30 am.
  $monday = (new DateTime())->modify('tomorrow')->modify('previous monday')->format('Y-m-d 02:30:00');
  $lastUpdated = $createDate->format('Y-m-d H:i:s');

  return ($lastUpdated < $monday);
}

$date_time_from_database = '2019-05-27 02:30:00'; // this date value comes from your database
$last_updated = new DateTime($date_time_from_database);  

if(databaseIsOutOfDate($last_updated)) {
  print "Updating database, please try again later";
  // trigger your update script
  die; // if you continue, you'll have race condition.
}

print "continue with script";


来源:https://stackoverflow.com/questions/56328209/php-scheduling-a-task-on-webhosting-without-ssh-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!