有的时候计划任务可能需要涉及到服务器的操作,如果是一些虚拟主机的用户可能没有此操作权限,现在就要写一个简单的计划任务脚本进行执行操作。
当前程序会在人访问的时候可以触发,因此需要全站操作都可以运行该方法。
数据库的结构已经在代码中列出了,一个表就可以完成了
/*计划任务*/
protected function plan(){
$sql = Db::name('syetem_plan') -> where('nextrun',' cache(true) -> find();
if(empty($sql)){
return;
}
//初始化时间到当前凌晨
$nextrun = strtotime('00:00');
/*
//数据库结构
$sql = [
"id" => 1,
"lastrun" => 0,
"nextrun" => 0,
"weekday" => -1,
"day" => -1,
"hour" => 1,
"minute" => 15,
];
*/
$str = '+';
if($sql['day'] >= 0){
$day = $sql['day'] -1;
$nextrun = strtotime(date('Y-m').'-1 00:00');
$str .= '1 month '.$day." day ";
}elseif($sql['weekday'] >= 1){
$weekday = ['','monday','tuesday','wednesday','thursday','friday','saturday','sunday'];
$day = $weekday[$sql['weekday']];
$str = 'next '.$day.' ';
//$nextrun = strtotime('next ',$time);
}
if($sql['hour'] >= 0){
$str .= '1 day ';
$str .= $sql['hour'].' hour ';
//$nextrun = strtotime($str,$nextrun);
}
if($sql['minute'] >= 0){
if($sql['hour'] < 0){
$str .= date('H')+1;
$str .= ' hour ';
}
$str .= $sql['minute'].' minute';
}
//TOD 以下部分为需要执行的任务,
//写入数据库更新时间
$nextrun = strtotime($str,$nextrun);
$data = [
'lastrun' => time(),
'nextrun' => $nextrun,
];
Db::name('syetem_plan') -> where('id',$sql['id']) -> update($data);
return;
}转载请注明:七彩悠悠博客 | 心悠悠 情悠悠 » php写的一个简单的计划任务

