Chapter 56. Timers, IO, and Idle Functions

Table of Contents
56.1. Timouts
56.2. Monitoring IO
56.3. Idle Functions

56.1. Timouts

You may be wondering how you make GTK do useful work when in main Gtk. Well, you have several options. Using the following function you can create a timeout function that will be called periodically.

$timer = Gtk->timeout_add( $interval, \&function, @function_data );

The first argument is the interval (in milliseconds) between calls to your function. The second argument is the function you wish to have called, and the third, the data passed to this callback function. The return value is an integer "tag" which may be used to stop the timeout by calling:

Gtk->timeout_remove( $timer );

You may also stop the timeout function by returning a false value from your callback function. Obviously this means if you want your function to continue to be called, it should return a true value.

The declaration of your callback should look something like this:

sub timeout_callback
  {
    my ( @data ) = @_;
    ...
}

56.2. Monitoring IO

A nifty feature of GDK (the library that underlies GTK), is the ability to have it check for data on a file descriptor for you (as returned by open() or socket()). This is especially useful for networking applications. The function:

$id = Gtk::Gdk->input_add( $source, $condition, \&function, @data );

takes a file descripter you want watched as the first argument, and the second argument specifies what you want GDK to look for. This may be one of:

As I'm sure you've figured out already, the third argument is the function you wish to have called when the above conditions are satisfied, and the fourth is the data to pass to this function.

The return value is a tag that may be used to stop GDK from monitoring this file descriptor using the following function:

Gtk::Gdk->input_remove( $id );

The callback function should be declared as:

sub input_callback
  {
    my ( $source, $condition, @data ) = @_;
    ...
  }

Where source and condition are as specified above.

56.3. Idle Functions

What if you have a function which you want to be called when nothing else is happening ?

$idle = Gtk->idle_add( \&function, @data );

This causes GTK to call the specified function whenever nothing else is happening. And, to remove that idle callback, you would use:

Gtk->idle_remove( $idle );

I won't explain the meaning of the arguments as they follow very much like the ones above. The function pointed to by the first argument to idle_add() will be called whenever the opportunity arises. As with the others, returning a false value will stop the idle function from being called.