Laravel Forge - Scheduling a Cron Job

Posted on June 02, 2014 | By Matt Stauffer


Warning: This post is over a year old. I don't always update old posts with new information, so some of this information may be out of date.

PHP by its nature acts in response to a request. A visitor comes to your URL, and your app spins up, processes the request, performs the appropriate actions in response, and then shuts down. Visit twenty pages in a row? This process happens twenty times in a row. But what about when you're not around?

We've already covered queues and queue workers, and we'll talk about daemons soon. But cron jobs are the simplest way to keep things moving in the background, rather than relying on user requests to perform all of your app's logic and heavy lifting. Let's set up our first cron job on Forge.

Forge Scheduler

Forge Add Cron Job Screen

Honestly, there's not much to explain here.

That's the best part about cron jobs on Forge: You no longer have to memorize the order of the time slots on the cron format. You no longer have to fight hosts who don't offer crons. Click the "Scheduler" tab on your Forge server, choose the path and frequency, hit Schedule Job, and you're done.

Command

The default path is php /home/forge/default/artisan scheduled:run, which shows you that the simplest use of cron in Laravel is to trigger Artisan commands.

We have an internal app that consumes the Harvest API. But it's painfully slow when we allow the users' visits to trigger the API sync. So now, we have this running every hour in the background:

php /home/forge/sauce/artisan harvest:sync

Note that you're not limited to Artisan commands. Run MySQL backups, run custom shell scripts, copy files around, or whatever else you'd prefer. If you can run it on the command line, you can run it here.

User

Determine the system user who's running this command. Keep it at forge unless you know what you're doing. :)

Frequency

This does what it says on the tin. Note that the custom schedule option allows you to use the familiar asterisk-style scheduler.

Forge Scheduler Options

A quick reminder of what that means:

From left to right, Minutes Hours Day-of-Month Month Day-of-Week

  • First asterisk = Minutes: 0-59
  • Second asterisk = Hours: 0-23
  • Third asterisk = Day of Month: 1 - 31
  • Fourth asterisk = Month: 1 - 12
  • Fifth asterisk = Day of Week: 0 - 6 (0 is Sunday, 6 is Saturday)

* means "every". So * * * * * means "every minute of every hour of every day of every month".

Logs

For any cron jobs that are running, you can view logs for the output of your cron jobs, so you can diagnose any errors (or just see that they're working).

View Forge Cron Logs

Conclucado

That's it! Go forth and schedule!


Comments? I'm @stauffermatt on Twitter


Tags: laravel  •  forge  •  cron