찾다
php教程php手册Use DJJob in CodeIgniter

In a web application, time consuming processes, like sending emails, you need make it asynchronous. In this blog, we will introduce how to make a job running in the background using DJJob and crontab or CLI. In the Rails world, you have ma

In a web application, time consuming processes, like sending emails, you need make it asynchronous. In this blog, we will introduce how to make a job running in the background using DJJob and crontab or CLI.

In the Rails world, you have many choices: Delayed Job, Resque, Sidekiq. Even in Rails 4.2, it introduced Active Job.

If you are using PHP, it may be inconvenient.But you also have some choice, for example DJJob, through the homepage, it’s a:

DJJob allows PHP web applications to process long-running tasks asynchronously. It is a PHP port of delayed_job (developed at Shopify), which has been used in production at SeatGeek since April 2010.

Like delayed_job, DJJob uses a jobs table for persisting and tracking pending, in-progress, and failed jobs.

Here we will write a simple exapmle, to use DJJob to send email in background.

At first your need to install DJJob by copy the PHP files and create tables.Here we will skip these steps. Let’s start by writing business code directly.

A job class is needed, it’s a normaly PHP class, you don’t need to extend any classes, or keep to any rules(all you need is to write a method named `perform`).

<?php Class Mail_job{
    private $_CI;
    private $config;
    private $to;
    private $subject;
    private $body;
    public function __construct($to, $subject, $body){
        $this->to = $to;
        $this->subject = $subject;
        $this->body = $body;
    }
    public function perform() {
        $this->_CI = &get_instance();
        $this->_CI->config->load('mail');
        $this->config = $this->_CI->config->item('mail_server');
        $config['protocol'] = 'smtp';
        $config['smtp_host'] = $this->config['smtp_host'];
        $config['smtp_port'] = $this->config['smtp_port'];
        $config['smtp_user'] = $this->config['smtp_user'];
        $config['smtp_pass'] = $this->config['smtp_pass'];
        $config['charset'] = 'utf-8';
        $config['wordwrap'] = TRUE;
        $config['newline'] = "\r\n";
        $config['crlf'] = "\r\n";
        $config['mailtype'] = 'html';
        $this->_CI->email->clear();
        $this->_CI->email->initialize($config);
        $this->_CI->email->from($from_email, 'no-reply');
        $this->_CI->email->to($to);
        $this->_CI->email->subject($subject);
        $this->_CI->email->message($body);
        return $this->_CI->email->send();
    }
}

Notcie:

job class’s __construct?should as simply as possible, it’s will affect the size of serialized class.

To use this job class, you will insert these code in your source:

DJJob::configure(['driver'=> 'mysql','host'=> $db->hostname,
            'dbname'=> $db->database,
            'user'=> $db->username,
            'password'=> $db->password]);
$mj = new Mail_job($to, $subject, $body, $mailtype);
DJJob::enqueue($mj, "email");

These code first do the database configuration, and then serialize the Mail_job?instance into database use DJJob::enqueue($mj, “email”); ?and the queue name is email(the sencond parameter).

Now we have saved a job into database, next let’s learn how to execute the job.

Our job executer will run in an console but not from a web browser, CodeIgniter support this use case by running Controller from CLI, for more infomation you can checkout the offical document?here.

We will create a Controller too, let’s name it to Queue_job?:

class Queue_job extends CI_Controller {
    function __construct(){
        parent::__construct();
        // this controller can only be called from the command line
        if (!$this->input->is_cli_request()) show_error('Direct access is not allowed');
    }
    function send_mail(){
        $db = $this->db;
        DJJob::configure(['driver'=> 'mysql','host'=> $db->hostname,
            'dbname'=> $db->database,
            'user'=> $db->username,
            'password'=> $db->password]);
        $worker = new \DJWorker(['queue' => 'email']);
        $worker->start();
    }
}

The main method is send_mail, this will first configurate the database an run a DJWorker. The DJWorker?will pickup jobs from database and run them, ?mark the job status, and lastly remove them from database if the job completed?successfully.

If you have finished the Controller, then you can call the Controller from CLI like this:

$ cd /path/to/project;
$ php index.php Queue_job send_mail

or make a cron job like:

0 10 * * * /path/to/php /path/to/project/index.php Queue_job send_mail

Conclusion

Though it’s not as easy as in Rails, but it’s realy simple to run jobs that kicked off from web browser by end-user and running in background asynchronous.

Notice:

If you job class with complex types, you will pay attention to the include path somewhere if you got an error.

Reference:

1. How to Run Cron Jobs in CodeIgniter

2. Writing Cron Jobs and Command Line Scripts in CodeIgniter

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.