PHP.GT

Quick start guide

In this guide we will build a tiny project with one cron script, one crontab file, and one command to run it.

[!TIP] In WebEngine projects, phpgt/cron is already installed and gt run will start the scheduler for local development. This guide is for getting the project running outside of WebEngine, or just to understand what’s going on under the bonnet.

1. Install the package

composer require phpgt/cron

This gives us the vendor/bin/cron executable and the PHP classes behind it.

2. Create a crontab file

In the project root, create a file called crontab:

* * * * * hello

This line means “run hello every minute”.

3. Create the matching script

Now create cron/hello.php:

<?php
echo "Hello from cron at ", date("Y-m-d H:i:s"), PHP_EOL;

The runner looks in the local cron/ directory when it sees a simple script name such as hello.

Project structure so far:

.
├── cron
│   └── hello.php
├── composer.json
└── crontab

4. Run jobs that are due now

From the project root:

vendor/bin/cron --now

Because the job runs every minute, it will run immediately.

The CLI itself prints scheduler status messages. By default it does not stream the child script’s own stdout or stderr, so real jobs usually write to a file, send an email, update a database row, or perform some other visible piece of work.

5. Keep the runner alive

If we want the process to wait for the next due time automatically:

vendor/bin/cron --watch

The runner prints status messages such as how many jobs just ran and when the next job is due.

6. Add another type of job

Cron jobs are not limited to files. For example, we can also call a static PHP method:

0 9 * * MON-FRI App\Task\Digest::send("team@example.com")

Or run a full shell command exactly as written:

30 2 * * * php bin/nightly-maintenance.php

Those two styles are explained in more detail in Static functions and shell commands.


Next, move on to Crontab syntax so we can read and write schedules confidently.