Crontab Job

Crontab jobs allow code to be automatically executed at set time intervals. Let's develop out a crontab job that automatically marks projects as halted that haven't been updated within 30 days. Within terminal run the following create crontab command:

apex create crontab disaster halt-projects

Open the newly generated file at /src/Disaster/Opus/Crontabs/HaltProjects.php and replace it with the following contents:

<?php
declare(strict_types = 1);

namespace App\Disaster\Opus\Crontabs;

use Apex\Svc\Db;
use Apex\App\Interfaces\Opus\CrontabInterface;

/**
 * Crontab job - HaltProjects
 */
class HaltProjects implements CrontabInterface
{

    /**
     * Whether or not to automatically execute this crontab job.
     */
    public bool $auto_run = true;

    /**
     * How often to run this crontab job.  
     * Must be formatted as the period letter followed by the number.
     *
     * For the period, I = Minute, H = Hour, D = Day, W = Week, M = Month, Q = Quarter, Y = Year
     *
     * For example, I30 = every 30 minutes, H3 = every 3 hours, W2 = every 2 weeks, et al.
     */
    public string $interval = 'D1';

    /**
     * Description of the crontab job
     */
    public string $description = 'Halt projects after 30 days of inactivity';

    #[Inject(Db::class)]
    private Db $db;


    /**
     * Process the crontab job
     */
    public function process():void
    {

        // Update datbase
        $this->db->query("UPDATE disaster_projects SET status = 'halted' WHERE updated_at < date_sub(now(), interval 30 day)");

    }

}

The $interval property is set to D1 meaning this code will be automatically executed once every day. The process() method then simply runs an SQL query against the database to change the status of any projects that have not been updated within 30 days to halted.

Manually Execute Crontab Jobs

If a crontab job ever needs to be manually executed instead of waiting for the next automated run, you can do so by running the crontab command, for example:

apex crontab disaster halt-projects

If there's a server configuration issue and crontab is not properly setup for example, all pending crontab jobs may be manually executed with the command:

apex crontab