Question

What is the best way to check, if a cronjob is already running?

I need a cronjob that checks, if there are new files in a folder and then do some stuff to this files. The cronjob should check every minute for new files. The problem is, that the cronjob itself could need more than one hour to execute.

How can i avoid to execute a cronjob multiple times?

Was it helpful?

Solution

Run the following command to see if crons are running:

service cron status

Or check the following table to see which cronjobs are running (empty (truncate!) the table and see if it get's repopulated to check if your crons are running the way you want it):

cron_schedule

OTHER TIPS

Best extension out there for this (it's free too):

https://github.com/AOEpeople/Aoe_Scheduler

I want to be able to check the cron table quite often, without the need to login or connect manually to the sql server. I did not want to install a new module, and therefore just use a very simple php page in a hidden folder:

<?php 

/**
 * src/pub/hidden/cronschedule.php
 */

// read Magento2 config
$conf = include('../../app/etc/env.php');

echo '<h1>Cron Jobs</h1>';

try {
    $DB_HOST = $conf['db']['connection']['default']['host'];
    $DB_USER = $conf['db']['connection']['default']['username'];
    $DB_PASS = $conf['db']['connection']['default']['password'];
    $DB_DBNM = $conf['db']['connection']['default']['dbname'];

    // instanciate db connection
    $dbh = new PDO('mysql:host=' . $DB_HOST . ';dbname=' . $DB_DBNM, $DB_USER, $DB_PASS);

    // prepare and execute sql statement
    $sql = 'SELECT * from cron_schedule order by scheduled_at desc limit 400;';
    $res = $dbh->query($sql);

    // output the list
    echo $res->rowCount() . ' records * Server time: ' . date('d.m.Y H:i:s');
    $firstRow = true;
    if ($res->rowCount() > 0) {
        echo '<table>';
        while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
            if ($firstRow) {
                echo '<tr>';
                foreach ($row as $fieldname => $field) {
                    echo '<th>' . $fieldname . '</th>';
                }
                echo '</tr>';
                $firstRow = false;
            }
            echo '<tr>';
            foreach ($row as $field) {
                echo '<td>' . $field . '</td>';
            }
            echo '</tr>';
        }
    }
    $dbh = null;
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
}

The list of cron jobs can then be seen via https://my.domain/hidden/cronschedule.php

One can improve the script by formatting the result via json, formatting the output as proper html, or by adding drop down fields for filters.

It is very important to password-protect the "hidden" directory. This could be via .htaccess.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top