PyGTK: How to display a systray icon from a cronjob

It is nice to give some user feedback when someting happen in a background application. For example when a cronjob is running it would be nice to show a systray icon.


When the cron-job runs the DISPLAY environment variable is not defined so your gtk application can’t access to xserver. So before importing pygtk you should check if DISPLAY is defined. If not just define it to default value “:0.0″.

import os
 
#if DISPLAY is not set, then set it to default ':0.0'
if len( os.getenv( 'DISPLAY', '' ) ) == 0:
	os.putenv( 'DISPLAY', ':0.0' )
 
import pygtk
pygtk.require("2.0")

But what happens if your gtk application really can’t connect to the xserver (xserver is not runnig, you are not logged in …). In this case your application should not try to use xserver related functions. For example when I try to use gtk.StatusIcon the application ends with a segmentation fault.

To check if your application can access to xserver just get the default display. If it is None then you can’t access it.

display = gtk.gdk.display_get_default()
if not display is None:
	...


Now, putting all together I made this simple application: notify.py.

 


Try it:

python notify.py

Now to try it from cron, you can add it in you crontab to be called every 10 minutes (use full path to notify.py):

( crontab -l; echo "0 * * * * python /FULLPATH/notify.py" ) | crontab -
( crontab -l; echo "10 * * * * python /FULLPATH/notify.py" ) | crontab -
( crontab -l; echo "20 * * * * python /FULLPATH/notify.py" ) | crontab -
( crontab -l; echo "30 * * * * python /FULLPATH/notify.py" ) | crontab -
( crontab -l; echo "40 * * * * python /FULLPATH/notify.py" ) | crontab -
( crontab -l; echo "50 * * * * python /FULLPATH/notify.py" ) | crontab -

Check your crontab:

crontab -l

you should see the lines with “python /FULLPATH/notify.py”.

To remove it from your crontab just call:

crontab -l | grep -v notify.py | crontab -

Tags: , , , ,

Leave a Reply