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
原文地址:Use DJJob in CodeIgniter, 感谢原作者分享。

如何在CodeIgniter中实现自定义中间件引言:在现代的Web开发中,中间件在应用程序中起着至关重要的作用。它们可以用来执行在请求到达控制器之前或之后执行一些共享的处理逻辑。CodeIgniter作为一个流行的PHP框架,也支持中间件的使用。本文将介绍如何在CodeIgniter中实现自定义中间件,并提供一个简单的代码示例。中间件概述:中间件是一种在请求

CodeIgniter中间件:加速应用程序的响应速度和页面渲染概述:随着网络应用程序的复杂性和交互性不断增长,开发人员需要使用更加高效和可扩展的解决方案来提高应用程序的性能和响应速度。CodeIgniter(CI)是一种基于PHP的轻量级框架,提供了许多有用的功能,其中之一就是中间件。中间件是在请求到达控制器之前或之后执行的一系列任务。这篇文章将介绍如何使用

在CodeIgniter框架中使用数据库查询构建器(QueryBuilder)的方法引言:CodeIgniter是一个轻量级的PHP框架,它提供了许多功能强大的工具和库,方便开发人员进行Web应用程序开发。其中一个令人印象深刻的功能是数据库查询构建器(QueryBuilder),它提供了一种简洁而强大的方法来构建和执行数据库查询语句。本文将介绍如何在Co

随着Web应用程序的不断发展,更加快速和高效地开发应用程序变得非常重要。并且,随着RESTfulAPI在Web应用程序中的广泛应用,对于开发人员来说,必须理解如何创建和实现RESTfulAPI。在本文中,我们将讨论如何使用CodeIgniter框架实现MVC模式和RESTfulAPI。MVC模式简介MVC(Model-Vie

CodeIgniter是一个轻量级的PHP框架,采用MVC架构,支持快速开发和简化常见任务。CodeIgniter5是该框架的最新版本,提供了许多新的特性和改进。本文将介绍如何使用CodeIgniter5框架来构建一个简单的Web应用程序。步骤1:安装CodeIgniter5下载和安装CodeIgniter5非常简单,只需要遵循以下步骤:下载最新版本

现今互联网时代,一款深受用户喜爱的网站必须具备简洁明了的前端界面和功能强大的后台管理系统,而PHP框架CodeIgniter则是一款能够让开发者快速搭建后台管理系统的优秀框架。CodeIgniter拥有轻量级、高效率、易扩展等特点,本文将针对初学者,详细说明如何通过该框架快速搭建一个后台管理系统。一、安装配置安装PHPCodeIgniter是一个基于PHP的

随着移动互联网的发展,即时通信变得越来越重要,越来越普及。对于很多企业而言,实时聊天更像是一种通信服务,提供便捷的沟通方式,可以快速有效地解决业务方面的问题。基于此,本文将介绍如何使用PHP框架CodeIgniter开发一个实时聊天应用。了解CodeIgniter框架CodeIgniter是一个轻量级的PHP框架,提供了一系列的简便的工具和库,帮助开发者快速

近年来,Web开发技术的进步和全球互联网应用的不断扩大,使得PHP技术应用面越来越广泛。作为一种快速开发的技术,其生态系统也在不断发展壮大。其中,CodeIgniter作为PHP开发领域中著名的框架之一,备受众多开发者的欢迎。本篇文章将介绍CodeIgniter框架的相关知识,以此为初学者提供一个入门的指引。一、什么是CodeIgniter框架?CodeIg


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

DVWA
Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、

PhpStorm Mac バージョン
最新(2018.2.1)のプロフェッショナル向けPHP統合開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

MinGW - Minimalist GNU for Windows
このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

ZendStudio 13.5.1 Mac
強力な PHP 統合開発環境
