Home 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`).

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

<?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();

    }

}

Copy after login

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:

1

2

3

4

5

6

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");

Copy after login

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?:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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();

    }

}

Copy after login

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:

1

2

$ cd /path/to/project;

$ php index.php Queue_job send_mail

Copy after login

or make a cron job like:

1

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

Copy after login

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

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement custom middleware in CodeIgniter How to implement custom middleware in CodeIgniter Jul 29, 2023 am 10:53 AM

How to implement custom middleware in CodeIgniter Introduction: In modern web development, middleware plays a vital role in applications. They can be used to perform some shared processing logic before or after the request reaches the controller. CodeIgniter, as a popular PHP framework, also supports the use of middleware. This article will introduce how to implement custom middleware in CodeIgniter and provide a simple code example. Middleware overview: Middleware is a kind of request

CodeIgniter middleware: Accelerate application responsiveness and page rendering CodeIgniter middleware: Accelerate application responsiveness and page rendering Jul 28, 2023 pm 06:51 PM

CodeIgniter Middleware: Accelerating Application Responsiveness and Page Rendering Overview: As web applications continue to grow in complexity and interactivity, developers need to use more efficient and scalable solutions to improve application performance and responsiveness. . CodeIgniter (CI) is a lightweight PHP-based framework that provides many useful features, one of which is middleware. Middleware is a series of tasks that are performed before or after the request reaches the controller. This article will introduce how to use

How to use the database query builder (Query Builder) in the CodeIgniter framework How to use the database query builder (Query Builder) in the CodeIgniter framework Jul 28, 2023 pm 11:13 PM

Introduction to the method of using the database query builder (QueryBuilder) in the CodeIgniter framework: CodeIgniter is a lightweight PHP framework that provides many powerful tools and libraries to facilitate developers in web application development. One of the most impressive features is the database query builder (QueryBuilder), which provides a concise and powerful way to build and execute database query statements. This article will introduce how to use Co

How to implement form validation for web applications using Golang How to implement form validation for web applications using Golang Jun 24, 2023 am 09:08 AM

Form validation is a very important link in web application development. It can check the validity of the data before submitting the form data to avoid security vulnerabilities and data errors in the application. Form validation for web applications can be easily implemented using Golang. This article will introduce how to use Golang to implement form validation for web applications. 1. Basic elements of form validation Before introducing how to implement form validation, we need to know what the basic elements of form validation are. Form elements: form elements are

How to enable administrative access from the cockpit web UI How to enable administrative access from the cockpit web UI Mar 20, 2024 pm 06:56 PM

Cockpit is a web-based graphical interface for Linux servers. It is mainly intended to make managing Linux servers easier for new/expert users. In this article, we will discuss Cockpit access modes and how to switch administrative access to Cockpit from CockpitWebUI. Content Topics: Cockpit Entry Modes Finding the Current Cockpit Access Mode Enable Administrative Access for Cockpit from CockpitWebUI Disabling Administrative Access for Cockpit from CockpitWebUI Conclusion Cockpit Entry Modes The cockpit has two access modes: Restricted Access: This is the default for the cockpit access mode. In this access mode you cannot access the web user from the cockpit

Is PHP front-end or back-end in web development? Is PHP front-end or back-end in web development? Mar 24, 2024 pm 02:18 PM

PHP belongs to the backend in web development. PHP is a server-side scripting language, mainly used to process server-side logic and generate dynamic web content. Compared with front-end technology, PHP is more used for back-end operations such as interacting with databases, processing user requests, and generating page content. Next, specific code examples will be used to illustrate the application of PHP in back-end development. First, let's look at a simple PHP code example for connecting to a database and querying data:

What are web standards? What are web standards? Oct 18, 2023 pm 05:24 PM

Web standards are a set of specifications and guidelines developed by W3C and other related organizations. It includes standardization of HTML, CSS, JavaScript, DOM, Web accessibility and performance optimization. By following these standards, the compatibility of pages can be improved. , accessibility, maintainability and performance. The goal of web standards is to enable web content to be displayed and interacted consistently on different platforms, browsers and devices, providing better user experience and development efficiency.

CodeIgniter middleware: Provides secure file upload and download functions CodeIgniter middleware: Provides secure file upload and download functions Aug 01, 2023 pm 03:01 PM

CodeIgniter middleware: Provides secure file upload and download functions Introduction: In the process of web application development, file upload and download are very common functions. However, for security reasons, handling file uploads and downloads often requires additional security measures. CodeIgniter is a popular PHP framework that provides a wealth of tools and libraries to support developers in building secure and reliable web applications. This article will introduce how to use CodeIgniter middleware to implement secure files

See all articles