php5.3下使用php管理crontab计划任务
php5.3或以上版本可以使用php管理crontab计划任务,下面我先来体验一下,有需要学习了解的朋友可进入参考.
1.使用php-crontab-manager管理计划任务
要求 PHP>=5.3,使用方法举例,代码如下:
use phpmanagercrontabCrontabManager; $crontab = new CrontabManager(); $crontab->enableOrUpdate('/tmp/my/crontab.txt'); $crontab->save();
로그인 후 복사
添加一个简单的计划任务,代码如下:
use phpmanagercrontabCrontabManager; $crontab = new Ssh2_crontab_manager(); $job = $crontab->newJob(); $job->on('* * * * *'); $job->onMinute('20-30')->doJob("echo foo"); $crontab->add($job); $job->onMinute('35-40')->doJob("echo bar"); $crontab->add($job); $crontab->save();
로그인 후 복사
php类文件,代码如下:
<?php Class Ssh2_crontab_manager { private $connection; private $path; private $handle; private $cron_file; function __construct($host = NULL, $port = NULL, $username = NULL, $password = NULL) { $path_length = strrpos(__FILE__, "/"); $this->path = substr(__FILE__, 0, $path_length) . '/'; $this->handle = 'crontab.txt'; $this->cron_file = "{$this->path}{$this->handle}"; try { if (is_null($host) || is_null($port) || is_null($username) || is_null($password)) throw new Exception("The host, port, username and password arguments must be specified!"); $this->connection = @ssh2_connect($host, $port); if (!$this->connection) throw new Exception("The SSH2 connection could not be established."); $authentication = @ssh2_auth_password($this->connection, $username, $password); if (!$authentication) throw new Exception("Could not authenticate '{$username}' using pasword: '{$password}'."); } catch(Exception $e) { $this->error_message($e->getMessage()); } } public function exec() { $argument_count = func_num_args(); try { if (!$argument_count) throw new Exception("There is nothing to exececute, no arguments specified."); $arguments = func_get_args(); $command_string = ($argument_count > 1) ? implode(" && ", $arguments) : $arguments[0]; $stream = @ssh2_exec($this->connection, $command_string); if (!$stream) throw new Exception("Unable to execute the specified commands: <br />{$command_string}"); } catch(Exception $e) { $this->error_message($e->getMessage()); } return $this; } public function write_to_file($path = NULL, $handle = NULL) { if (!$this->crontab_file_exists()) { $this->handle = (is_null($handle)) ? $this->handle : $handle; $this->path = (is_null($path)) ? $this->path : $path; $this->cron_file = "{$this->path}{$this->handle}"; $init_cron = "crontab -l > {$this->cron_file} && [ -f {$this->cron_file} ] || > {$this->cron_file}"; $this->exec($init_cron); } return $this; } public function remove_file() { if ($this->crontab_file_exists()) $this->exec("rm {$this->cron_file}"); return $this; } public function append_cronjob($cron_jobs = NULL) { if (is_null($cron_jobs)) $this->error_message("Nothing to append! Please specify a cron job or an array of cron jobs."); $append_cronfile = "echo '"; $append_cronfile.= (is_array($cron_jobs)) ? implode("n", $cron_jobs) : $cron_jobs; $append_cronfile.= "' >> {$this->cron_file}"; $install_cron = "crontab {$this->cron_file}"; $this->write_to_file()->exec($append_cronfile, $install_cron)->remove_file(); return $this; } public function remove_cronjob($cron_jobs = NULL) { if (is_null($cron_jobs)) $this->error_message("Nothing to remove! Please specify a cron job or an array of cron jobs."); $this->write_to_file(); $cron_array = file($this->cron_file, FILE_IGNORE_NEW_LINES); if (emptyempty($cron_array)) { $this->remove_file()->error_message("Nothing to remove! The cronTab is already empty."); } $original_count = count($cron_array); if (is_array($cron_jobs)) { foreach ($cron_jobs as $cron_regex) $cron_array = preg_grep($cron_regex, $cron_array, PREG_GREP_INVERT); } else { $cron_array = preg_grep($cron_jobs, $cron_array, PREG_GREP_INVERT); } return ($original_count === count($cron_array)) ? $this->remove_file() : $this->remove_crontab()->append_cronjob($cron_array); } public function remove_crontab() { $this->remove_file()->exec("crontab -r"); return $this; } private function crontab_file_exists() { //开源代码phprm.com return file_exists($this->cron_file); } private function error_message($error) { die("<pre style='color:#EE2711'>ERROR: {$error}
로그인 후 복사
项目地址:https://github.com/MediovskiTechnology/php-crontab-manager
2.Ssh2_crontab_manager 关于php管理计划任务的详细教程
具体内容参考:http://net.tutsplus.com/tutorials/php/managing-cron-jobs-with-php-2/
参考资料:http://stackoverflow.com/questions/4421020/use-php-to-create-edit-and-delete-crontab-jobs
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사
어 ass 신 크리드 그림자 : 조개 수수께끼 솔루션
3 몇 주 전
By DDD
Windows 11 KB5054979의 새로운 기능 및 업데이트 문제를 해결하는 방법
2 몇 주 전
By DDD
Atomfall에서 크레인 제어 키 카드를 찾을 수 있습니다
3 몇 주 전
By DDD
어 ass 신 크리드 섀도우 - 대장장이를 찾고 무기 및 갑옷 커스터마 화 잠금 해제 방법
1 몇 달 전
By DDD
<s> : 데드 레일 - 모든 도전을 완료하는 방법
3 몇 주 전
By DDD

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제
Gmail 이메일의 로그인 입구는 어디에 있나요?
7621
15


Cakephp 튜토리얼
1389
52


Steam의 계정 이름 형식은 무엇입니까?
89
11


Win11 활성화 키 영구
70
19


NYT 연결 힌트와 답변
31
136

