Help me setup a cron job on Ubuntu
Hi :) I wanted to have a every-20 mins-notifier kind of app and decided to develop one by myself using Tomboy notes. I read up about crontab and set a job through the sudo crontab -e
command.
*/20 * * * * python /home/phantom/Desktop/alarm.py 2>/home/phantom/Desktop/whatswrong.log
And my python code would go like:
#!/usr/bin/env python
import dbus, gobject, dbus.glib
# Get the D-Bus session bus
bus = dbus.SessionBus()
# Ac开发者_C百科cess the Tomboy D-Bus object
obj = bus.get_object("org.gnome.Tomboy","/org/gnome/Tomboy/RemoteControl")
# Access the Tomboy remote control interface
tomboy = dbus.Interface(obj, "org.gnome.Tomboy.RemoteControl")
# Display the Start Here note
tomboy.DisplayNote(tomboy.FindNote("alert"))
I don't know anything about the DBus interface but read a tutorial that uses DBus to interface with Tomboy and came up with the above code.
When I run the code manually I could open the Tomboy note(alert message) but with the cron I get the following error which I couldn't understand. Please me help me out. Thanks :)
Traceback (most recent call last):
File "/home/phantom/Desktop/try.py", line 4, in <module>
bus = dbus.SessionBus()
File "/usr/lib/pymodules/python2.6/dbus/_dbus.py", line 219, in __new__
mainloop=mainloop)
File "/usr/lib/pymodules/python2.6/dbus/_dbus.py", line 108, in __new__
bus = BusConnection.__new__(subclass, bus_type, mainloop=mainloop)
File "/usr/lib/pymodules/python2.6/dbus/bus.py", line 125, in __new__
bus = cls._new_for_bus(address_or_type, mainloop=mainloop)
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.Spawn.ExecFailed: /bin/dbus- launch terminated abnormally with the following error: Autolaunch error: X11 initialization failed.
The fundamental issue is that an running X session is required in your case, and when CRON script runs, it runs without such a session (it actually runs detached from any terminal). Dbus executable needs to be able to initialize X session (it doesn't actually need a running X).
There are a couple of solutions:
- A similar problem is described here. Their solution is to run Xvfb or similar to allow all processes access to X, even if they don't actually display anything.
- A different approach is described here. See, if just exporting the relevant variables (you can do that in Python or wrap them in the script CRON launches and put them right before the call to python interpreter) solves your problem. Note, the thread discusses dbus-launch, which is a daemon start process, but dbus-send is under the same umbrella here.
- Just set the DISPLAY variable in your script as described here. That should be sufficient for DBUS to run.
I think the 3rd solution is the easiest, but now you have more than one.
Don't do a sudo
crontab, but just do a crontab -e
for the crontab to be run as your userprofile and provide the full path to your system python, you can get this by which python
.
精彩评论