使用PHP安排Cron作业

时间:2018-03-21 07:57:57

标签: php cron

<?php
    ini_set('display_errors','1'); 
    error_reporting(E_ALL);
    include_once 'dbConnect.php';

    $startdate = trim($_POST['startdate']);
    $enddate = trim($_POST['enddate']);


    if (connect()){
        global $conn;       

        $query="SELECT electionNo FROM election ORDER BY electionNo DESC LIMIT 1";
        $details = $conn->query($query);

        while ($rows = $details->fetch_assoc())
            $election = $rows['electionNo'];

        $election=$election+1;

        $liststart= explode("T",$startdate);            
        $listend= explode("T",$enddate);    

        $start=$liststart[0]." ".$liststart[1];
        $end=$listend[0]." ".$listend[1];

        $year = substr($listend[0],0,4);

        $insertquery = "INSERT INTO election(electionNo,year,startTime,endtime) VALUES('$election','$year','$start','$end')";

        $insert = $conn->query($insertquery);
        if ($insert)
            echo 'Registered Successfully';     
        else
            echo 'No good';     
    }               
?>

我想将$start传递给 Cron作业以安排作业。例如,如果$start = '2018-03-20 12:00:00',则 Cron作业应如下所示:

  

00 12 20 03 * php /home/Dropbox/WebServer/paramGen.php

这意味着paramGen.php必须在2018-03-20的12:00运行。

这是否可行,如果可行,如何将$start传递给 cron作业

1 个答案:

答案 0 :(得分:1)

以下是构建cron命令的方法:

$start = '2018-03-20 12:00:00';
  $date=strtotime($start);
  $str= date('i',$date)." ".date('H',$date)." ".date('d',$date)." ".date('m',$date)." \* php /home/Dropbox/WebServer/paramGen.php";

然后

exec("echo $str >> cronfile")

希望这会有所帮助