Magento Tips & Tricks

Running Magento shell commands in background

Some magento cli commands can take ages to complete. You start it in terminal, but it require the terminal window to stay alive till the process complete. For example

php bin/magento queue:consumer:start media.storage.catalog.image.resize

There can be easily 1 million of images and the process can take several days. To bypass this you can run task in background.

Detach process from the terminal

append & to a command to detach it from the terminal. Two notes:

  • it is better to redirect output to a file, so you can check it
  • you can use ps to check that process is still running
php bin/magento queue:consumer:start media.storage.catalog.image.resize > /var/log/image.resize.log &

Use “disown”

disown

disown [-ar] [-h] [jobspec ...]
Without options, each jobspec is removed from the table of active jobs. If the -h option is given, the job is not removed from the table, but is marked so that SIGHUP is not sent to the job if the shell receives a SIGHUP. If jobspec is not present, and neither the -a nor -r option is supplied, the current job is used. If no jobspec is supplied, the -a option means to remove or mark all jobs; the -r option without a jobspec argument restricts operation to running jobs.

This method is good when you already started the process and now you realize it takes too long to complete.

  • press ctrl-z to interrupt the process
  • run bg to make it run in the background
  • run jobs to check a list of all background processes
  • run disown %1 (replace 1 with the process number output by jobs) to detach the process from the terminal

Or you can run it like this

$ COMMAND & disown

Use screen

screen

$ screen -dm COMMAND
-d -m
Start screen in detached mode. This creates a new session but doesn’t attach to it.

Or you can

  • run screen to start a new screen session
  • run php bin/magento queue:consumer:start media.storage.catalog.image.resize
  • exit screen ( CTRL+A CTRL+D ) and return to initial shell
  • run screen -r to reconnect to your screen session

Magento 2: Console Commands Shortcuts
Complete CLI commands list

Leave a Reply

Your email address will not be published. Required fields are marked *