I decided to write a quick tutorial on setting up the task scheduling for Laravel in Ubuntu after recently setting it up and realizing there wasn’t many good tutorials online. And the official Laravel documentation doesn’t give much direction if you aren’t experienced with cronjobs. The following tutorial assumes that you have a basic knowledge of ssh, the Ubuntu terminal, and using editors from the terminal.
Creating/Unlocking Ubuntu Root Account
To enable root logins in Ubuntu you have to set a password for the root account and then unlock the account. If you don’t already have a password for the root account, you can make one by executing the following command in the terminal:
sudo passwd root
This will give you a prompt to enter a new password. Enter the new password twice and be sure to store it somewhere safe. Then you must unlock the root account, you can do this by entering the following command in the terminal:
sudo passwd -u root
This will return the following information in the terminal
passwd: password expiry information changed
Locking Ubuntu Root Account
If you want to lock the root account later, you can do so by entering the following command in the terminal:
sudo passwd -l root
Running Ubuntu as Root
You can either login to your ubuntu server with the root account that you just unlocked and created the password for, or you can use the root terminal by using the following command:
Setting up the Cronjob in Ubuntu
On the task scheduling page of the official Laravel documentation, you can find the following line of code:
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
This code calls the laravel scheduler every minute and then runs the commands that you have defined in your “App/Console/Kernel.php” file of your Laravel root directory. While your logged in as the root user or using the root terminal with the sudo -i command run the following command in the terminal:
You should be prompted to choose an editor like nano or vi, use whatever editor you’re comfortable using.
Scroll down to the bottom of the file and enter the code from the Laravel task scheduling page that was copied above and then save your file.
Thats it! After you save your cronjob should run every minute and check your Kernel.php file for scheduled tasks.