How to automatically change your desktop background / wallpaper

This tutorial explains how to change automatically your desktop wallpaper in Ubuntu.

Ubuntu Unity already has a dynamic desktop wallpaper that changes throughout the day, which are selected from the /usr/share/backgrounds folder, but after a while a I got bored to see always the same images so I wanted to use my collection of images from the APOD, Astronomy Picture of the Day, website.

I thought that I could simply set a folder in System Settings -> Appearance but actually the only folder that you can select is the whole ~/Pictures folder, while I wanted to use only the ~/Pictures/Wallpapers. To solve my problem I could edit the /usr/share/backgrounds/contest/precise.xml file, but this means that I have to update that file every time I download a new picture from APOD, so I had to find my own solution.

The idea is quite simple:

  • select a random file from ~/Pictures/Wallpapers
  • change the desktop background setting from the command line
  • use a cron job to schedule the wallpaper change every 15 minutes

Select a Random File

This can be solved easily with a couple of lines in Python like this:

import os,random
return random.choice(os.listdir('/home/your-name/Pictures/Wallpapers'))

You can copy in your /home/your-name/bin directory a more usable version of this script from my Github repository random-file,

Change the Desktop Background from the Command Line

To change the desktop background from the command line you can use gsettings command:

$ gsettings set org.gnome.desktop.background picture-uri "file:///path/to/wallpaper.jpg"

Be aware that gsettings is a new command introduced in GNOME3 and Unity, if you use the old GNOME2 you have to use gconftool:

$ gconftool-2 --type=string --set /desktop/gnome/background/picture_filename /path/to/wallpaper.jpg

To find out what version you have, run:

$ gnome-session --version

You can put this command in a bash script to change your background but actually is not going to work when it is called from cron jobs, because the DBUS_SESSION_BUS_ADDRESS environment variable need to be set first.

Again, You can copy change-wallpaper from my Github repository in your /home/your-name/bin.

As I am using Ubuntu 12.04, my script calls gsettings, but you're free to fork my dd-scripts and send me a pull request if you write a version for Gnome2.

Set a Cron Job

Now it's only a question of telling your system to change automatically the background every 15 minutes by editing your user's crontab table:

$ crontab -e

Then add these lines:

# Edit this file to introduce tasks to be run by cron.
# m h  dom mon dow   command
*/15 *  * * * /home/your-name/bin/change-wallpaper

Great! Enjoy your new desktop wallpapers!