首页 > php教程 > php手册 > 正文

Use DJJob in CodeIgniter

php中文网
发布: 2016-06-06 20:13:41
原创
1493人浏览过

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

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号