IT박스

PHP를 사용하여 크론 작업을 만드는 방법은 무엇입니까?

itboxs 2020. 9. 4. 07:04
반응형

PHP를 사용하여 크론 작업을 만드는 방법은 무엇입니까?


cron 작업을 처음 사용합니다. 어떻게 쓰는지도 모르겠어요. 인터넷에서 검색을 해봤지만 아직 잘 모르겠습니다. 매분 내 코드를 실행할 크론 작업을 만들고 싶습니다. 나는 그것을 만들기 위해 PHP를 사용하고 있습니다. 그것은 작동하지 않습니다.

run.php (1 분마다 실행되는 코드)

<?php

echo "This code will run every minute";

?>

cron.php

<?php

$path = dirname(__FILE__);
$cron = $path . "/run.php";
echo exec("***** php -q ".$cron." &> /dev/null");

?>

이 두 파일이 같은 폴더에 있다고 가정합니다.

내가 잘못한 코드입니까? 틀렸다면 친절하게 고쳐주세요.


지금까지 찾은 PHP 코드에 대한 가장 좋은 설명입니다.

http://code.tutsplus.com/tutorials/managing-cron-jobs-with-php--net-19428

요컨대 :

새 작업을 예약하는 구문이 언뜻보기에는 어렵게 보일 수 있지만 실제로는 일단 분할하면 이해하기가 비교적 간단합니다. 크론 작업에는 항상 5 개의 열이 있으며 각 열은 시간순 '연산자'와 그 뒤에 실행할 전체 경로 및 명령을 나타냅니다.

* * * * * home / path / to / command / the_command.sh

각 연대순 열은 작업 일정과 특정 관련이 있습니다. 다음과 같습니다.

Minutes represents the minutes of a given hour, 0-59 respectively.
Hours represents the hours of a given day, 0-23 respectively.
Days represents the days of a given month, 1-31 respectively.
Months represents the months of a given year, 1-12 respectively.
Day of the Week represents the day of the week, Sunday through Saturday, numerically, as 0-6 respectively.

여기에 이미지 설명 입력

예를 들어, 매월 1 일 오전 12시에 작업을 예약하려는 경우 다음과 같이 표시됩니다.

00 1 * * home / path / to / command / the_command.sh

매주 토요일 오전 8시 30 분에 작업을 실행하도록 예약하려면 다음과 같이 작성합니다.

30 8 * * 6 home / path / to / command / the_command.sh

일정을 더욱 맞춤화하는 데 사용할 수있는 여러 운영자도 있습니다.

Commas is used to create a comma separated list of values for any of the cron columns.
Dashes is used to specify a range of values.
Asterisksis used to specify 'all' or 'every' value

전체 기사를 보려면 링크를 방문하십시오.

  1. 수동으로 입력 / 편집하려는 경우 cronjob의 형식은 무엇입니까?
  2. SSH2 라이브러리와 함께 PHP를 사용하여 편집 할 crontab을 사용자로 인증하는 방법.
  3. crontab 항목을 인증, 편집 및 삭제하는 데 필요한 모든 방법이 포함 된 전체 PHP 클래스.

cron.php를 실행하려는 것과 같은 방식으로 다른 PHP 스크립트를 실행할 수 있습니다. 하지만 CLI 인터페이스를 통해해야합니다.

#!/usr/bin/env php
<?php
# This file would be say, '/usr/local/bin/run.php'
// code
echo "this was run from CRON";

그런 다음 crontab에 항목을 추가하십시오.

* * * * * /usr/bin/php -f /usr/local/bin/run.php &> /dev/null

run.php 스크립트에 실행 권한이있는 경우 / usr / bin / php 부분없이 crontab에 직접 나열 될 수 있습니다. 스크립트의 'env php'부분은 실제로 PHP 코드를 실행하는 데 적합한 프로그램을 찾습니다. 따라서 '실행 가능'버전의 경우 파일에 실행 권한을 추가하십시오.

chmod +x /usr/local/bin/run.php

그런 다음 crontab에 다음 항목을 추가하십시오.

* * * * * /usr/local/bin/run.php &> /dev/null

Added to Alister, you can edit the crontab usually (not always the case) by entering crontab -e in a ssh session on the server.

The stars represent (* means every of this unit):

[Minute] [Hour] [Day] [Month] [Day of week (0 =sunday to 6 =saturday)] [Command]

You could read some more about this here.


Type the following in the linux/ubuntu terminal

 crontab -e 

select an editor (sometime it asks for the editor) and this to run for every minute

*       *       *       *       *       /usr/bin/php path/to/cron.php &> /dev/null

why you not use curl? logically, if you execute php file, you will execute that by url on your browser. its very simple if you run curl

while(true)
{
    sleep(60); // sleep for 60 sec = 1 minute

    $s = curl_init();
    curl_setopt($s,CURLOPT_URL, $your_php_url_to_cron); 
    curl_exec($s); 
    curl_getinfo($s,CURLINFO_HTTP_CODE); 
    curl_close($s);
}

$command = "php ".CRON_PATH.php ";
if(substr(php_uname(), 0, 7) == "Windows"){
pclose(popen("start /B ". $command, "r"));
}else{
shell_exec($command ." > /dev/null &");
}


Create a cronjob like this to work on every minute

*       *       *       *       *       /usr/bin/php path/to/cron.php &> /dev/null

First open your SSH server with username and password and change to the default root user(User with all permissions) then follow the steps below,

  1. enter the command crontab -l now you will see the list of all cronjobs.
  2. crontab -e모든 cron 작업이있는 파일을 입력 하면 열립니다.
  3. cronjob 일정으로 파일을 편집하고 파일을 min hr dayofmonth month dayofweek pathtocronjobfile저장합니다.
  4. 이제 응답이 crontab: installing new crontab다시 표시됩니다. 크론 작업이 나열 될 크론 작업 목록을 확인합니다.

이를 해결하는 간단한 방법이 있습니다. 1 분마다 cron으로 php 파일을 실행할 수 있으며, php 실행 파일 내부에서 "if"문이 "지금"과 같이 실행될 때 실행할 수 있습니다.

<?/** suppose we have 1 hour and 1 minute inteval 01:01 */

$interval_source = "01:01";
$time_now = strtotime( "now" ) / 60;
$interval = substr($interval_source,0,2) * 60 + substr($interval_source,3,2);


if( $time_now % $interval == 0){
/** do cronjob */
}

function _cron_exe($schedules) {
        if ($obj->get_option('cronenabledisable') == "yes") {
            // $interval = 1*20;
            $interval = $obj->get_option('cronhowtime');
            if ($obj->get_option('crontiming') == 'minutes') {
                $interval = $interval * 60;
            } else if ($obj->get_option('crontiming') == 'hours') {
                $interval = $interval * 3600;
            } else if ($obj->get_option('crontiming') == 'days') {
                $interval = $interval * 86400;
            }
            $schedules['hourlys'] = array(
                'interval' => $interval,
                'display' => 'cronjob'
            );
            return $schedules;
        }

}

참고 URL : https://stackoverflow.com/questions/18737407/how-to-create-cron-job-using-php

반응형