DEV Community

Imam Ali Mustofa
Imam Ali Mustofa

Posted on

Watch and Testing Cronjob using PHP

At one point, when I was suddenly stupid (often), I asked myself "How can I see and test a cronjob?"

Google Results

Of course I will not open all the answers given by google, because as a lazy internet user like me it is impossible to see Google search results until the last page!

On the first page I found most of them give explanation about "How to use cronjob" and "How to see running cronjob" as well as "How to view log of cronjob".

But... what I need is to create it temporarily and not have to edit the cronjob template. How to do it?

How do i do that?

A few months ago I came across an interesting library on Github made by walkor called crontab

Walkor made it very easy, thanks a lot walkor.

Let's try to make it more real, first we install the library via composer

composer require workerman/crontab
Enter fullscreen mode Exit fullscreen mode

After installing the library, create a file in the folder that you used for testing during the development process.

<?php
use Workerman\Worker;
require __DIR__ . '/../vendor/autoload.php';

use Workerman\Crontab\Crontab;
$worker = new Worker();

$worker->onWorkerStart = function () {
    // Execute the function in the first second of every minute.
    new Crontab('1 * * * * *', function(){
        echo date('Y-m-d H:i:s')."\n"; // your script here!!!
    });
};

Worker::runAll();
Enter fullscreen mode Exit fullscreen mode

See what will happen in the terminal below

asciicast

With this library we can use cronjob expressions as usual.

Thanks to walkor πŸ₯³

Top comments (0)