Why Doesn't Notify-Send Work In Cron?

Published September 21, 2024

Problem: Notify-Send Not Working in Cron Jobs

The notify-send command, used for sending desktop notifications, often fails to work when run through cron jobs. This issue can be a problem for users trying to set up automated notifications for system tasks or events.

Solving the Notify-Send Cron Problem

Setting the Environment Variables

To make notify-send work in cron jobs, you need to set the environment variables. The DISPLAY variable tells the system which display to show the notification on. For most users, this is ":0.0".

The XDG_RUNTIME_DIR variable points to a directory for user-specific temporary files. This variable helps the notification system find the place to store and access runtime data.

Tip: Check Your Display Variable

To confirm your DISPLAY variable, open a terminal and run:

echo $DISPLAY

If it returns ":0" or ":0.0", you can use this in your cron job. If it's different, use the value returned by this command.

Solution for Ubuntu and i3 Window Manager

For Ubuntu users with the i3 window manager, you can change your crontab entry to include these variables. Here's how to set up a cron job that sends a notification every minute:

* * * * * XDG_RUNTIME_DIR=/run/user/$(id -u) notify-send Hey "this is dog!"

This crontab entry:

  • Runs every minute (five asterisks)
  • Sets the XDG_RUNTIME_DIR variable to the user-specific directory
  • Uses $(id -u) to get the current user's ID, making it work for any user
  • Runs the notify-send command with a message

By adding these environment variables to your crontab entry, you can get desktop notifications to work from your cron jobs.