If you’ve found yourself needing to schedule commands via CRON after a reboot without manually logging in, you might be tempted to enable automatic login (without a password). Obviously, this would work, but it would leave the session open, which may not be recommended in terms of security and privacy. Therefore, in this brief article, I propose a series of solutions to handle this.
Let’s assume that we want to run a graphical application like a browser: To ensure that a cron job that opens a browser runs at the scheduled time, even after a system reboot and without logging in, you need to make sure that the cron job runs as a background service and does not depend on the user’s session. This involves using the system’s cron and ensuring that the browser can run without a user graphical environment.
1. Edit the system cron (root)
User cron (executed with crontab -e) only works when the user is logged in. To ensure that cron runs even after a reboot, you must use the system’s cron, which runs as root.
To edit the system cron:
sudo crontab -e
This will open the cron file as a superuser, where you can add your task.
2. Install a browser that can run in “headless” mode
Browsers like Chrome and Firefox have a “headless” mode that allows them to run without a graphical environment (i.e., without a user session). You can configure cron to use this mode.
-
- Install Chrome headless:
sudo apt update
sudo apt install chromium-browser
-
- Example of a cron job to open a URL in headless mode:
In the cron file (which you opened with sudo crontab -e), add a line like the following:
0 8 * * * /usr/bin/chromium-browser --headless --disable-gpu --no-sandbox --remote-debugging-port=9222 http://yoursite.com
This will open the URL http://yoursite.com every day at 8:00 AM.
3. Ensure cron starts at boot
Ubuntu has the cron service enabled by default, but if you ever disabled it, make sure to enable it:
sudo systemctl enable cron
sudo systemctl start cron
4. Optional: Run cron in a graphical environment
If you really need the browser to open with a graphical interface (and not in headless mode), you can use the following trick to start the browser with the graphical server (X) after reboot:
Add the DISPLAY environment variable to the cron command:
0 8 * * * DISPLAY=:0 /usr/bin/firefox http://yoursite.com
This will open Firefox in the graphical environment.
Note: Make sure the graphical server (Xorg or Wayland) is active and configured to run after reboot.
5. Run cron after reboot, even if the system was powered off
To ensure that cron jobs run even if the system was powered off during the scheduled time, you can install anacron, which is a version of cron that runs missed jobs:
sudo apt install anacron
Then, add your cron task using anacron, and it will run the next time the system is available.
