Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do Heroku workers work ?

Heroku supports multiple types of dyno configurations and allows us to set both a web and a worker process type for an app, for example like so:

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

The web dyno will handle the web traffic, meanwhile the worker dyno type can be used as a background job (e.g.: to process a queue.)

The docs didn't make it clear to me how these workers function, i.e.: how do they start? behave?

In particular:

  • Are they run just once at deployment? Or are they run repeatedly (if so when)?
  • Do they have a maximum execution time?
  • Is it okay to use an endless loop inside of them? Or should I trigger them somehow?

If I go for a simple hello world:

myworker.php
<?php
error_log( "Hello world. This is the worker talking." );
?>

Then (after deploy or restart) heroku logs --tail --ps worker shows me only this:

2017-08-31T17:46:55.353948+00:00 heroku[worker.1]: State changed from crashed to starting
2017-08-31T17:46:57.834203+00:00 heroku[worker.1]: Starting process with command `php worker/mailer.php`
2017-08-31T17:46:58.452281+00:00 heroku[worker.1]: State changed from starting to up
2017-08-31T17:46:59.782480+00:00 heroku[worker.1]: State changed from up to crashed
2017-08-31T17:46:59.773468+00:00 heroku[worker.1]: Process exited with status 0
2017-08-31T17:46:59.697976+00:00 app[worker.1]: Hello world. This is the worker talking.

Is it the expected behavior?

(I'm not very used to using PHP from the command-line, which is what workers seem to be doing and might explain some of my confusion.)

Background: I'm trying to understand how they work for my own sake, but also to help me decide whether I should use a worker or a clock for a homemade mailing/newsletter system I'm adapting to Heroku.

like image 878
Fabien Snauwaert Avatar asked Sep 06 '26 00:09

Fabien Snauwaert


1 Answers

You probably have already find out, but here is my experience with it for anyone looking for the answer:

  • Are they run just once at deployment? Or are they run repeatedly (if so when)?

They will run once deployed and keep running unless an exit command is issued or if the script returns an error. On my experience, when an error occurs, it's interrupted immediately and restarted after some time (which seems random). I'm not sure if it will restart when a clean exit is executed.

  • Do they have a maximum execution time?

No. But keep in mind that all dynos are restarted once per day.

  • Is it okay to use an endless loop inside of them? Or should I trigger them somehow?

Yes. Most of my uses involves a sleep in loop followed by calling the main script function.

like image 61
Bruno Cantuaria Avatar answered Sep 07 '26 14:09

Bruno Cantuaria