Set Up Cron Jobs to Run PHP Scripts on DirectAdmin

A Cron Job is a scheduled task that runs scripts or commands automatically at set intervals. Common uses include sending daily emails, clearing caches overnight, running database backups, or triggering PHP scripts on a schedule. This step-by-step guide shows you how to configure Cron Jobs on DirectAdmin Hosting to run PHP scripts automatically.

What is a Cron Job?

Cron is a time-based job scheduler on Linux that runs tasks automatically at defined intervals. Scheduling uses a Cron Expression with five fields:

* * * * * command
│ │ │ │ └── Day of week (0-7, 0/7 = Sunday)
│ │ │ └──── Month (1-12)
│ │ └────── Day of month (1-31)
│ └──────── Hour (0-23)
└────────── Minute (0-59)

Common Cron Expression Examples

Cron Expression Reference for Common Schedules

Beyond the five-field syntax basics, here is a practical reference table of expressions used in real hosting scenarios, along with their typical use cases:

Expression Schedule Typical Use Case
*/5 * * * * Every 5 minutes Queue processing, WP-Cron replacement
0 */6 * * * Every 6 hours Data sync, cache clearing
0 2 * * * Daily at 02:00 Nightly database backup
0 9 * * 1-5 Monday–Friday at 09:00 Daily business report email
0 0 1,15 * * 1st and 15th of each month Bi-monthly invoice generation
0 23 * * 0 Every Sunday at 23:00 Weekly full-site backup

Not sure about the syntax? Use the free Cron Expression Generator — enter the schedule you want in plain English and get the correct expression instantly.

Setting Up a Cron Job in DirectAdmin

  1. Log in to DirectAdmin
  2. Go to Advanced Features → Cron Jobs
  3. Fill in the Minute / Hour / Day / Month / Weekday fields
  4. Enter the command to run
  5. Click Add

Commands to Run PHP Scripts

Format 1 — Direct PHP Binary

/usr/local/php83/bin/php /home/username/public_html/cron/script.php

Format 2 — php-cli

/usr/bin/php /home/username/public_html/cron/script.php

Format 3 — wget (HTTP-based Cron)

wget -q -O /dev/null "https://yourdomain.com/cron/run.php" > /dev/null 2>&1

Format 4 — curl

curl -s "https://yourdomain.com/cron/run.php" > /dev/null 2>&1

Tip: Always use full absolute paths for both the PHP binary and the script file. Cron runs in a minimal environment without the same PATH variables as a normal shell session. If unsure of the PHP binary path, run which php in SSH.

Writing Cron-Friendly PHP Scripts

A script designed to run via cron should handle locking, error reporting, and environment differences from web requests. Here are the three most important patterns:

Prevent Overlapping Runs with a Lock File

If your cron fires every 5 minutes but the script takes 8 minutes to complete, a second instance will start before the first finishes, potentially causing data corruption or doubled work.

<?php
$lockFile = '/home/username/cron.lock';
if (file_exists($lockFile)) {
    // If lock is older than 10 minutes, it is stale — remove it
    if (time() - filemtime($lockFile) < 600) {
        exit("Script already running\n");
    }
}
file_put_contents($lockFile, getmypid());

try {
    // ... main work ...
} finally {
    unlink($lockFile); // always remove lock, even on error
}

Capture Errors and Send Alerts

Cron jobs are invisible — they run in the background and fail silently unless you build in error handling. Add this block at the top of every cron script:

<?php
set_error_handler(function($errno, $errstr, $errfile, $errline) {
    $msg = date('Y-m-d H:i:s')." ERROR [$errno] $errstr in $errfile:$errline\n";
    file_put_contents('/home/username/cron-error.log', $msg, FILE_APPEND);
    mail('[email protected]', 'Cron Error Alert', $msg);
});

register_shutdown_function(function() {
    $error = error_get_last();
    if ($error && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR])) {
        $msg = date('Y-m-d H:i:s')." FATAL: ".$error['message']."\n";
        file_put_contents('/home/username/cron-error.log', $msg, FILE_APPEND);
    }
});

Set the Correct Timezone

Cron runs in the server timezone, which is often UTC. If your schedule logic depends on local time, set the timezone explicitly at the top of your script:

<?php
date_default_timezone_set('Asia/Bangkok'); // UTC+7

// For database operations, also set MySQL timezone:
$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'user', 'pass');
$pdo->exec("SET time_zone = '+07:00'");
echo date('Y-m-d H:i:s'); // Bangkok local time

Practical Cron Job Examples

Send daily report email at 08:00

0 8 * * * /usr/bin/php /home/username/public_html/send-email.php

Clear cache every night at midnight

0 0 * * * /usr/bin/php /home/username/public_html/clear-cache.php

Replace WP-Cron with a Real Cron Job

Add to wp-config.php: define('DISABLE_WP_CRON', true);

Then add this Cron Job:

*/5 * * * * /usr/bin/php /home/username/public_html/wp-cron.php > /dev/null 2>&1

Shared Hosting Limitations and How to Work Around Them

Shared hosting has constraints that differ significantly from a VPS. Understanding them upfront will save you from unexpected failures in production.

Constraint Shared Hosting Reality Workaround
Minimum frequency Every 1 minute (DirectAdmin) Sufficient for most tasks
Execution timeout Often capped at 60–300 seconds Add set_time_limit(0) in script
Memory limit 128–512 MB depending on plan Run php -d memory_limit=256M
Output handling Unredirected output may be emailed to the crontab owner Append > /dev/null 2>&1 to every command
PATH environment Cron starts with a minimal PATH — binaries may not resolve Always use absolute paths for PHP binary and scripts

For scripts that run longer than 5 minutes, consume significant memory, or need to run more frequently than once per minute, consider upgrading to a VPS where there are no shared resource restrictions and you can use a full system crontab.

Verifying Your Cron Job Runs

Have your script write a log entry each time it executes so you can verify it later:

<?php
file_put_contents('/home/username/cron.log',
    date('Y-m-d H:i:s') . " - Script ran\n", FILE_APPEND);
// ... your script code

Hosting with Full Cron Job Support

AsiaGB Hosting supports Cron Jobs via DirectAdmin with PHP 7.4 / 8.2 / 8.3. Starting from just 500 THB/year with 99% Uptime.

View Hosting Plans

View all cheap Thailand web hosting plans →