如何使用cron作业调度动态函数? [英] How to schedule dynamic function with cron job?

查看:266
本文介绍了如何使用cron作业调度动态函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何安排动态(自动填充数据)功能在保存的时间每天自动运行?



我想说,我有一个表格按钮被点击它发送数据到功能,其中发布数据。我只是想自动化,所以我不必按下按钮。

 < ul> 
<?php
foreach($ Class-> retrieveData as $ data)
{
< form method =postaction =>
< li>
< input type =hiddenname =name>'。$ data ['name']。'< br /
< input type =hiddenname =description>'。$ data ['description']。< br />
< input type =submitname =post_datavalue =Post>
< / li>
< / forms>
}
?>
< / ul>

现在,表单将数据传递给函数。

  if(isset($ _ POST ['post_data']))//如果post_data按钮被点击,那么它运行myFunction()
{
myFunction();
}

myFunction()
{
$ name = $ _POST ['name'];
$ description = $ _POST ['description'];
}

我试过以下操作,但问题是Cron Job只能运行整个.php文件,我检索从MySQL运行的保存时间。

  foreach($ Class-> getTime )as $ timeData)
{
$ timeHour = $ timeData ['timeHour'];
$ timeMinute = $ timeData ['timeMinute'];

$ hourMin = date('H:i');
$ timeData =''。$ timeHour。':'。$ timeMinute。'';

if($ hourMin == $ timeData)
{
运行myFunction。
}
}

$ hourMin 是当前小时:分钟,它与从Mysql自动运行的保存时间进行匹配。因此,如果 $ hourMin == $ timeData ,那么函数将运行。



如何运行Cron Job以自动运行 myFunction()如果 $ hourMin 等于 $ timeData



所以...

 列表1 =将在上午10点运行
列表2 =将在下午12点运行
列表3 = at 2pm

上午10点,中午12点,下午2点是从MySQL中检索但基于每个列表ID的 $ timeHour $ timeMinute



EDIT



@randomSeed,

  1)我可以计划cron作业。 
2)$ name和$ description都将是数组,所以下面是我想要完成的。

$ name = array(
'Jon',
'Steven',
'Carter'
);

$ description = array(
'Jon是一个伟大的人。',
'Steven有一个外向字符',
'Carter是一个可怕的人。 '
);

如果计划时间正确,我想从$ name和$ description解析第一个数组。



在数据库中我有以下

  postDataTime表

+ ---- + --------- + ---------- + ------------ + ----- --- +
| iD | timeDay | timeHour | timeMinute | postiD |
+ -------------------------------------- + ------ - +
| 1 | * | 9 | 0 | 21 |
| ---- | --------- | ---------- | ------------ | ------ - |
| 2 | * | 10 | 30 | 22 |
| ---- | --------- | ---------- | ------------ | ------ - |
| 3 | * | 11 | 0 | 23 |
+ ---- | --------- + ---------- + ------------ + ------ - +

iD =在上传时自动递增。
timeDay = *是每天(cron工作样式)
timeHour =运行脚本的一天的时间
timeMinute =运行脚本的小时的分钟
postiD =这是位于另一个表中的帖子的id(n + 1关系)

如果很难理解.. 什么是奎奴亚藜

  if(time()== 10:30(from MySQL postiD = 22))
{
// run myFunction with在该时间检索的数据ex:

$ postiD ='22';
$ name ='Steven';
$ description ='Steven有一个外出字符。

//上面是将在窗体中的$ _POST中,将
//发送到myFunction()
}

我只想根据保存到MySQL的时间来计划一切,就像我在顶部显示的那样(postDataTime表)。 (我会显示我已经尝试,但我已经搜索了无数小时的一个例子,我想要完成,但我找不到任何东西,我尝试不起作用。)



我认为我可以使用exec()函数,但从它似乎不允许我运行函数,否则我会做以下..

  $ time = '10:30'; 
if($ time == time())
{
exec(myFunction());
}


解决方案

strong> 2种方式,虽然只有一种方式可以做您想做的事情;




  • 第一种方式要求您具有访问权限和权限可更改cron-jobs服务器端(例如通过PHP或其他方式)。根据操作系统有教程: Nix


  • 第二种方法会靠近你想要的东西,但没有分钟精确度,你会在每个周期最多2分钟松开。 (见下文外形)。




第一路完美方式




  • 只要用户使用所需的数据时间点击该用户的表单创建一个唯一的cron任务




如果您没有这些权限,可以使用3d零件服务,例如
www.easycron.com 他们还提供了一个有限的
查询的免费版本。他们还提供 REST API 方法来管理(CRUDE)
cron任务。




第二路不完美的方式




  • 添加一个新的 VARCHAR 列,我今天将其命名为,这将确保任务将只运行



-

  + ---- + --------- + ---------- + ------------ + -------- + ---------- + 
| iD | timeDay | timeHour | timeMinute | postiD |今天|
+ -------------------------------------- + ------ - + ---------- +
| 1 | * | 9 | 0 | 21 | 30-05-04 |
| ---- | --------- | ---------- | ------------ | ------ - | ---------- +
| 2 | * | 10 | 30 | 22 | |
| ---- | --------- | ---------- | ------------ | ------ - | ---------- +
| 3 | * | 11 | 0 | 23 | |
+ ---- | --------- + ---------- + ------------ + ------ - + ---------- +




  • 之后创建一个php文件,我调用它 crontask.php 我们将每个 5 分钟


  • 将其添加到cronjob面板中:


  • 0,5 * * * * / usr / bin / php /www/virtual/username/crontask.php> / dev / null 2>< / c>< / c> c>档案




-

 code><?php 
// include()数据库配置文件这里与mysql_connect等...
// include()所需的文件ex。

$ cron_cycle = 5; //设置它等于cron命令行中使用的内容
$ today = date('Y-m-d');
if($ result = mysql_query(SELECT * FROM postDataTime WHERE today!='{$ today}')){
while($ row = mysql_fetch_array($ result,MYSQL_ASSOC)){
$ postID = $ row ['postID'];
$ timeHour =(int)$ row ['timeHour'];
$ current_hours =(int)date('H'); // current hours
$ current_minutes =(int)date('i'); // current minutes
$ timeMinute =(int)$ row ['timeMinute'];
//强制在最近的周期运行
$ timeMinute =($ timeMinute%$ cycle === 0)? $ timeMinute:toCloser($ timeMinute,$ cron_cycle);
if($ current_hours === $ timeHour& $ current_minutes === $ timeMinute){
//确保我们已经为此用户运行了cron ...
mysql_query(UPDATE postDataTime SET today ='{$ today}'WHERE postID ='{$ postID}');
myFunction($ postID);
}
}
}
函数toCloser($ n,$ x = 5){
$ j =(round($ n)%$ x === 0)? round($ n):(round(($ n + $ x / 2)/ $ x)* $ x);
return($ j- $ n)> = round($ x / 2)? ($ j- $ x):$ j;
}

?>



功能说明:



假设cron shedule每5分钟运行一次,lat说我们在20:00点,现在cron将运行在20:05,20:10,20:15,20:20等等...

然后假设在我们的数据库中我们有这些时间

  Jonh: 05,
马里奥:20:32,
luke:20:48,
大卫:20:57,
吉米:20:06,
Eddy:20: 16

当脚本检查那些时候它将运行如下:

 在20:05  - > run 20:05 Jonh,20:06 Jimmy 
at 20:10 - >在20:15运行null
- >运行20:16 Eddy
at 20:20 - >运行null
等等....

如你所见,最坏情况 2分钟。我认为这是公平的! ;)


I want to know how I can schedule a dynamic(auto populated data) function to auto run everyday at saved time?

Let's say I have a form that once the button is clicked it sends the data to the function, which the posts the data. I simply want to automate that so that I don't have to press the button.

<ul>
    <?php 
    foreach($Class->retrieveData as $data)
    {
        <form method="post" action="">
            <li>
                <input type="hidden" name="name">'.$data['name'].'<br/>
                <input type="hidden" name="description">'.$data['description'].'<br/>
                <input type="submit" name="post_data"  value="Post">
            </li>
        </form>
    }
    ?>
</ul>

Now, the form will pass the data to the function.

if(isset($_POST['post_data'])) // if post_data button is clicked then it runs myFunction()
{
    myFunction();
}

myFunction()
{
    $name        = $_POST['name'];
    $description = $_POST['description'];
}

I tried doing the following but the problem is that Cron Job can only run the whole .php file, and I am retrieving the saved time to run from MySQL.

foreach($Class->getTime() as $timeData)
{
    $timeHour    = $timeData['timeHour'];
    $timeMinute = $timeData['timeMinute'];

    $hourMin    = date('H:i');
    $timeData   = ''.$timeHour.':'.$timeMinute.'';

    if($hourMin == $timeData)
    {
        run myFunction.
    }
}

$hourMin is the current hour:minute which is being matched against a saved time to auto run from Mysql. So if $hourMin == $timeData then the function will run.

How can I run Cron Job to auto run myFunction() if the $hourMin equals $timeData?

So...

List 1 = is to be runned at 10am
List 2 = is to be runned at 12pm
List 3 = is to be runned at 2pm

The 10am, 12pm, 2pm is the $timeHour and $timeMinute that is retrieved from MySQL but based on each list id's.

EDIT

@randomSeed,

1) I can schedule cron jobs.
2) $name and $description will all be arrays, so the following is what I am trying to accomplish.

$name = array(
    'Jon',
    'Steven',
    'Carter'
);

$description = array(
    'Jon is a great person.',
    'Steven has an outgoing character.',
    'Carter is a horrible person.'
);

I want to parse the first arrays from both $name and $description if the scheduled time is correct.

In database I have the following

postDataTime table

+----+---------+----------+------------+--------+
| iD | timeDay | timeHour | timeMinute | postiD |
+--------------------------------------+--------+
| 1  | *       | 9        | 0          | 21     |
|----|---------|----------|------------|--------|
| 2  | *       | 10       | 30         | 22     |
|----|---------|----------|------------|--------|
| 3  | *       | 11       | 0          | 23     |
+----|---------+----------+------------+--------+

iD         = auto incremented on upload.
timeDay    = * is everyday (cron job style)
timeHour   = Hour of the day to run the script
timeMinute = minute of the hour to run script
postiD     = this is the id of the post that is located in another table (n+1 relationship)

If it's difficult to understand.. what is quinoa

if(time() == 10:30(time from MySQL postiD = 22))
{
    // run myFunction with the data that is retrieved for that time ex:

    $postiD = '22';
    $name   = 'Steven';
    $description = 'Steven has an outgoing character.';

    // the above is what will be in the $_POST from the form and will be
    // sent to the myFunction()
}

I simply want to schedule everything according to the time that is saved to MySQL as I showed at the very top(postDataTime table). (I'd show what I have tried, but I have searched for countless hours for an example of what I am trying to accomplish but I cannot find anything and what I tried doesn't work.).

I thought I could use the exec() function but from what it seems that does not allow me to run functions, otherwise I would do the following..

$time = '10:30';
if($time == time())
{
    exec(myFunction());
}

解决方案

you have 2 ways, although only one will do exactly what you want to do;

  • 1st way requires that you have access and privileges to change cron-jobs server side (example via PHP or other). Depending on what OS there are tutorials: Win , Nix

  • 2nd way will do something close to what you want but without the minutes precision, you will loose at max 2 minutes each cycle. (see exaplanation below).

1st Way perfect way

  • As soon as the user hit the form create a unique cron-task for that user using the desired datatime.

if you don't have those privileges you can use 3d part service like www.easycron.com they also offer a Free version with limited query. they also provide a REST API method to manage (CRUDE) cron-tasks.

2nd Way imperfect way

  • add a new VARCHAR column, i called it today with this we will ensure that the task will run only once per day.

-

+----+---------+----------+------------+--------+----------+
| iD | timeDay | timeHour | timeMinute | postiD |   today  |
+--------------------------------------+--------+----------+
| 1  | *       | 9        | 0          | 21     | 30-05-04 |
|----|---------|----------|------------|--------|----------+
| 2  | *       | 10       | 30         | 22     |          |
|----|---------|----------|------------|--------|----------+
| 3  | *       | 11       | 0          | 23     |          |
+----|---------+----------+------------+--------+----------+

  • after that create a php file i called it crontask.php we will call it each 5 minutes

  • add this to your cronjob panel:

  • 0,5 * * * * /usr/bin/php /www/virtual/username/crontask.php > /dev/null 2>&1

  • in the crontask.php file

-

<?php
// include() Database Config file here with mysql_connect etc...
// include() the required files ex. the file where myFunction reside...

$cron_cycle = 5; // set it equal to what used in cron command-line
$today = date('Y-m-d');
if($result = mysql_query("SELECT * FROM postDataTime WHERE today != '{$today}'")){
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { 
        $postID = $row['postID'];
        $timeHour = (int) $row['timeHour'];
        $current_hours = (int) date('H'); // current hours
        $current_minutes = (int) date('i'); // current minutes
        $timeMinute = (int) $row['timeMinute'];
        // force to run at the closest cycle
        $timeMinute = ($timeMinute % $cycle === 0) ? $timeMinute : toCloser($timeMinute, $cron_cycle); 
        if( $current_hours === $timeHour && $current_minutes === $timeMinute ){
            // ensure that we have already runned a cron for this user...
            mysql_query("UPDATE postDataTime SET today = '{$today}' WHERE postID = '{$postID}'");
            myFunction($postID);
        }
    }
}
function toCloser($n,$x=5) {
    $j = (round($n)%$x === 0) ? round($n) : (round(($n+$x/2)/$x)*$x);
    return ($j-$n) >= round($x/2) ? ($j-$x) : $j;
}

?>

Explanation of the function:

Assuming that the cron shedule runs each 5 minutes, lat's say we are at 20:00 o'clock, now the cron will run at 20:05, 20:10, 20:15, 20:20 and so on...

then assuming in our DB we have those time

Jonh  : 20:05, 
Mario : 20:32, 
luke  : 20:48, 
David : 20:57, 
Jimmy : 20:06, 
Eddy  : 20:16

when the script checks against those times it will run as below:

at 20:05 -> run 20:05 Jonh, 20:06 Jimmy
at 20:10 -> run null
at 20:15 -> run 20:16 Eddy
at 20:20 -> run null
and so on....

As you see you would loose in the worst case 2 minutes each time. I think it's fair enough! ;)

这篇关于如何使用cron作业调度动态函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆