Can't get cron to output a GUI message / how to make user aware cron is being executed

MyCatsHat asked:

I need to run, on Ubuntu 18.04, via cron a script, that I want, among other things, to display to the user a message when it is being run so that he is aware that cron is being run (perhaps there are also ways to do this that somehow don’t involve any GUI-related things; if yes, do let me know).

But since cron runs in its own, minimal environment, I wasn’t able to figure out how to do that.

I tried various approaches and the most promising seemed to explicitly assign DISPLAY and start a terminal with this display assigned to it and inside that terminal to run a command that displayes a message, meaning in myscript.sH I have two lines

export DISPLAY=:0 XAUTHORITY=~/.Xauthority 
gnome-terminal --display=:0.0 -- bash -c "xmessage -center -timeout 10 'ATTENTION. CRON IS RUN';exec bash"

When I run in my own terminal, without cron being involved, gnome-terminal --display=:0.0 -- bash -c "xmessage -center -timeout 10 'ATTENTION. CRON IS RUN';exec bash" this works (of course, in my terminal I wouldn’t need to start another terminal and could simpy run xmessage -center -timeout 10 'ATTENTION. CRON IS RUN' …).

But cron complains with the following message (I’m redirecting the outputs of what cron execute to a file, so that I can see what went wrong):

No protocol specified
Unable to init server: Could not connect: Connection refused

If I instead place xmessage -center -timeout 10 'ATTENTION. CRON IS RUN' in, cron complains

No protocol specified
Error: Can't open display: :0

How can I get either this command, or any other GUI message to be displayed? I don’t really care through what system the message is displayed, as long as the user is alerted in some way that right now cron is being executed.

My answer:

You can use the notify-send application to send a notification to the logged in user’s desktop. This program is in the libnotify-bin package.

For example:

notify-send --icon install "Cron job" "It's done, boss"

You may wish to background this. In my testing, I found that it would hang if no user was logged in at the time. It could just be a bug in my version, but you should be prepared for things to go wrong.

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.