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.
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") import gtk import threading import time #GTK main loop thread class GTKMainThread(threading.Thread): def run(self): gtk.main() #get default display. None means it can't connect to xserver display = gtk.gdk.display_get_default() statusIcon = None #if the display is not None show status icon if not display is None: #start a gtk loop in another thread gtk.gdk.threads_init() GTKMainThread().start() try: statusIcon = gtk.StatusIcon() statusIcon.set_from_stock( gtk.STOCK_INFO ) statusIcon.set_visible( True ) statusIcon.set_tooltip(_("Back In Time: take snapshot ...")) except: pass #do something here print "Begin" time.sleep( 5 ) #wait 5 seconds print "End" #hide status icon if not statusIcon is None: statusIcon.set_visible( False ) #quit GTK main look if not display is None: gtk.main_quit()
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 -lyou should see the lines with “python /FULLPATH/notify.py”.
To remove it from your crontab just call:
crontab -l | grep -v notify.py | crontab -
