首页 php教程 php手册 Use DJJob in CodeIgniter

Use DJJob in CodeIgniter

Jun 06, 2016 pm 08:13 PM
codeigniter use web

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 Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前 By 尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

如何在CodeIgniter中实现自定义中间件 如何在CodeIgniter中实现自定义中间件 Jul 29, 2023 am 10:53 AM

如何在CodeIgniter中实现自定义中间件

CodeIgniter中间件:加速应用程序的响应速度和页面渲染 CodeIgniter中间件:加速应用程序的响应速度和页面渲染 Jul 28, 2023 pm 06:51 PM

CodeIgniter中间件:加速应用程序的响应速度和页面渲染

如何使用Golang实现Web应用程序的表单验证 如何使用Golang实现Web应用程序的表单验证 Jun 24, 2023 am 09:08 AM

如何使用Golang实现Web应用程序的表单验证

在CodeIgniter框架中使用数据库查询构建器(Query Builder)的方法 在CodeIgniter框架中使用数据库查询构建器(Query Builder)的方法 Jul 28, 2023 pm 11:13 PM

在CodeIgniter框架中使用数据库查询构建器(Query Builder)的方法

如何从驾驶舱Web用户界面启用管理访问 如何从驾驶舱Web用户界面启用管理访问 Mar 20, 2024 pm 06:56 PM

如何从驾驶舱Web用户界面启用管理访问

PHP在Web开发中是属于前端还是后端? PHP在Web开发中是属于前端还是后端? Mar 24, 2024 pm 02:18 PM

PHP在Web开发中是属于前端还是后端?

CodeIgniter中间件:提供安全的文件上传和下载功能 CodeIgniter中间件:提供安全的文件上传和下载功能 Aug 01, 2023 pm 03:01 PM

CodeIgniter中间件:提供安全的文件上传和下载功能

如何使用PHP框架CodeIgniter快速搭建一个后台管理系统 如何使用PHP框架CodeIgniter快速搭建一个后台管理系统 Jun 27, 2023 am 09:46 AM

如何使用PHP框架CodeIgniter快速搭建一个后台管理系统

See all articles