【问题标题】:Steps to Write php script for cron job to execute a function [closed]为cron作业编写php脚本以执行函数的步骤[关闭]
【发布时间】:2013-05-10 01:36:24
【问题描述】:

我需要实现一个每天早上 8:00 运行的 cron 作业。我不知道需要做什么。 cron 应该在这个文件上运行一个函数 greet()。

<?php
    class Person {
     public $age=0;
     public  $isalive=false;
     public $name;
     public $msg;
     public $isAlive=true;
     public $firstname;
     public $lastname;

     public function __construct($fname,$lname,$age){
        $this->firstname=$fname;
        $this->lastname=$lname;
        $this->age=$age;
        $this->name=$fname." ".$lname;
        //$this->isAlive=$isAlive;
     }

         public function greet(){
             echo "$this->name says $this->msg my age is $this->age <br> am I alive:$this->isAlive";
         }
    }
     $teacher = new Person('boring','12345',12345);
     $student = new Person('Swapnil','Shende',24);
     echo $student->age;

     ?>

【问题讨论】:

  • “我需要实现一个每天早上 8:00 运行的 cron 作业。我不知道需要做什么。” — 尝试阅读 cron 手册。

标签: php mysql cron


【解决方案1】:

转到cron选项卡并像这样打开它

crontab -e

然后添加这一行

* 8 * * *   filename.php

filename.php 是你的文件名

同时编辑你的 file.php 以在最后调用这些函数

 $teacher = new Person('boring','12345',12345);
 $student = new Person('Swapnil','Shende',24);
 $student->greet();
 $teacher->greet();

【讨论】:

  • 但我需要编写 php 脚本来安排 cron 从该文件运行函数 greet()。
  • 这是 cron 作业的功能,它会为您安排它,只需编辑您的 file.php 以在最后调用该函数,就像这样 $student->greet();和 $teacher->greet();
  • 感谢这提供了一个更好的主意。
  • @rahulRaj 你欢迎干杯和快乐编码:)
  • 为此,您需要在文件开头添加一个 hashbang (#!/usr/bin/php),否则系统将不知道如何运行 PHP 文件。或者,您可以直接在您的 cron 行中添加它 (/usr/bin/php /path/to/script.php)。
【解决方案2】:
crontab -e
* 8 * * *  file.php

file.php 包含的位置:

<?php
include ('Person.class.php');
$teacher = new Person('boring','12345',12345);
$student = new Person('Swapnil','Shende',24);
$teacher->greet();
$student->greet();
?>

并从你的班级中删除这部分

$teacher = new Person('boring','12345',12345);
$student = new Person('Swapnil','Shende',24);
echo $student->age;

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2014-06-30
    • 2019-06-05
    • 2014-04-16
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    相关资源
    最近更新 更多