Heroku scheduler execute a PHP file Heroku scheduler execute a PHP file heroku heroku

Heroku scheduler execute a PHP file


The default PHP buildpack on Heroku does not currently have PHP CLI support, so you can only use it to serve web requests via Apache and not for scripts in worker dynos. However, this is possible if you are using a PHP buildpack that does have CLI support.

To test it out, I forked the PHP buildpack, switched out the PHP binary with one that was compiled with CLI support, and put together small demo of running a scheduled PHP job on Heroku. See the project's readme for step-by-step instructions. To use this fork on an existing app, set the buildpack with:

$ heroku config:add BUILDPACK_URL=https://github.com/ryanbrainard/heroku-buildpack-php.git

Note, the release script in my fork sets up the PATH to resolve the php executable in /app/bin/php with just php, unlike the default buildpack that woud require using the absolute path.


How to run a PHP script with Heroku Scheduler?

Testing and setting up the job

With a directory structure and Procfile looking something like this:

├─ Procfile├─ web/├── (your webfiles)├─ worker/└── myscript.php

Procfile:

web: vendor/bin/heroku-php-apache2 web/worker: php worker/myscript.php

Then you can test your worker from the command-line like so:

heroku run worker

To schedule a job, go into Heroku Scheduler and add the job in a similar fashion, but without the heroku run segment (else you'll get bash: heroku: command not found errors), just:

worker

Or, alternatively, directly:

php worker/myscript.php

Checking on the job

You can see the job in the app's logs. e.g.:

2017-09-01T14:19:37.397210+00:00 heroku[scheduler.9540]: Starting process with command `php worker/myscript.php` 

Notes

  • The worker name in the Procfile could be set to something else. e.g.: myworker, mysuperduperscript, etc.
  • I included a web section, but it's optional if all you want is a worker / background service and don't need to serve files on the web.

Alternative: if, for whatever reason, you'd rather perform a GET/POST request on a URL, you can use the Temporize Scheduler add-on.