Table of Contents
Inside this article we will see the concept Step by Step How To Setup Cron Jobs in CodeIgniter 4 Tutorial. Article contains classified information about Executing scheduled tasks in CodeIgniter 4 using Cron Jobs.
A Cron job, often known as a Cron task in Unix-like operating systems, is a time-based scheduler. It enables you to automate and plan the execution of specified commands or scripts at predefined intervals or durations.
These scheduled tasks can be made to run at specific times and dates or at regular intervals such as every minute, hour, day, week, or month.
Read More: How To Send Emails Using GMail SMTP and PHPMailer 6
Cron jobs are often used for a variety of tasks, including system maintenance, backups, data updates, sending automatic emails, retrieving data from other sources, and executing routine scripts.
Let’s get started.
CodeIgniter 4 Installation
To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.
$ composer create-project codeigniter4/appstarter codeigniter-4
Assuming you have successfully installed application into your local system.
Environment (.env) Setup
When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env
Either we can do via renaming file as simple as that. Also we can do by terminal command.
Open project in terminal
$ cp env .env
Above command will create a copy of env file to .env file. Now we are ready to use environment variables.
Enable Development Mode
CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.
Open .env file from root.
# CI_ENVIRONMENT = production
// Do it to
CI_ENVIRONMENT = development
Now application is in development mode.
What is CodeIgniter Task Scheduler?
CodeIgniter Task Scheduler makes cronjob scheduling in your application simple, versatile, and powerful. Instead of creating several cronjobs on each server where your application runs, create a single cronjob that points to the script, and all of your tasks will be scheduled in your code.
Read More: Laravel 10 Authentication with Laravel UI Tutorial
It also includes CLI tools to help you manage tasks, a Debug Toolbar collector, and other features.
Let’s see the steps to install and work with it.
Installation via Composer
Open your project terminal and run this command.
$ composer require daycry/cronjob
You should see in your terminal as:

Also, this package provides manual installation as well.
Manual Installation
Download this repo and then enable it by editing app/Config/Autoload.php.
Read More: How To Clear Complete Application Caches in Laravel 10
Add the Daycry\CronJob namespace to the $psr4 array. For example, if you copied it into app/ThirdParty,
$psr4 = [
'Config' => APPPATH . 'Config',
APP_NAMESPACE => APPPATH,
'App' => APPPATH,
'Daycry\CronJob' => APPPATH .'ThirdParty/cronjob/src',
];
Once you do the installation, you should see a command list of cron jobs inside php spark CLI.

Package Configuration to Application
Again, back to terminal and run this command.
$ php spark cronjob:publish
Once, you will run that. It will publish a file with name “CronJob.php” inside /app/Config folder.
Execute migration command to run pending migrations of application:
$ php spark migrate -all
All done with the setup.
Now, let’s create a job and scheduled it to run.
Create a Cron Job (Remove Unverified Users and Backup it)
This is only a demonstration code. You can use your own job concept in your application as per need.
Read More: How To Create and Download Zip File in Laravel 10 Tutorial
Here, we are removing unverified users from database after 24 hours and also creating a backup of those users into a different table. After all activity also we are maintaining application logs.
Open terminal and create a controller file.
$ php spark make:controller Background --suffix
It will create a file with name BackgroundController.php inside /app/Controllers folder.
Open controller file and write this complete code into it.
<?php namespace App\Controllers\Cron; use App\Controllers\BaseController; use App\Models\LogModel; use App\Models\RemovedUserModel; use App\Models\UserModel; class BackgroundController extends BaseController { private $db; public function __construct() { $this->db = db_connect(); } public function removeUnverifiedUsers() { $userObject = new UserModel(); $userData = $userObject->where("created_at <= NOW() - INTERVAL 1 DAY")->where([ "email_verified" => "0", ])->get()->getResultArray(); //echo $this->db->getLastQuery(); if (!empty($userData)) { $removedUserObject = new RemovedUserModel(); $data = array(); foreach ($userData as $user) { $data[] = array( "name" => $user['name'], "email" => $user['email'], "password" => $user['password'], "email_token" => $user['email_token'], "email_verified" => $user['email_verified'], ); $userObject->delete($user['id']); } $logObject = new LogModel(); if ($removedUserObject->insertBatch($data)) { $data = [ "type" => "removed_user", "log_msg" => count($data) . " Users removed due to unverified emails", ]; } else { $data = [ "type" => "removed_user", "log_msg" => "Failed to remove users", ]; } $logObject->insert($data); } } }
Now, job is ready. Next to link with task scheduler.
Add Cron Job To CodeIgniter Task Scheduler
Open CronJob.php from /app/Config folder.
You will see a lot of code inside above file. We need to work only on init method of it. Rest you can do other settings as well as per documentation.
<?php namespace Config; use CodeIgniter\Config\BaseConfig; use Daycry\CronJob\Scheduler; class CronJob extends \Daycry\CronJob\Config\CronJob { //... //... other code stuff /* |-------------------------------------------------------------------------- | Cronjobs |-------------------------------------------------------------------------- | | Register any tasks within this method for the application. | Called by the TaskRunner. | | @param Scheduler $schedule */ public function init(Scheduler $schedule) { $schedule->url(base_url('cron/remove-users'))->named("RemoveUnverfiedUsers")->daily(); } }
Enable CronJob For Tasks
Back to project terminal and run this command:
$ php spark cronjob:enable
It will enable CronJob processor.
Read More: How To Query To Get Single Row Data in Laravel 10 Tutorial
You can also verify it by running this command:
$ php spark cronjob:list
List of all cron jobs of your application.

Add CronJob Processor To Crontab
Back to your terminal, run this command.
$ crontab -e
If you run that, it will open a terminal editor (nano editor) to add your cron jobs processors.
Add your job to run once in a day.
* * * * * cd /path-to-your-project && php spark cronjob:run >> /dev/null 2>&1
Once you add your code, just save it. Now, you have a job inside your crontab.
If everything went well, you should be able to see that your job will execute automatically every day at 00:00.
We hope this article helped you to learn Step by Step How To Setup Cron Jobs in CodeIgniter 4 Tutorial in a very detailed way.
Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.
If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.