Reputation:
i'd like to make a daemon in Vala which only executes a task every X seconds. I was wondering which would be the best way:
I don't want it to eat too many resources when it's doing nothing..
Upvotes: 5
Views: 630
Reputation: 813
You can use GLib.Timeout.add_seconds
the following way:
Timeout.add_seconds (5000, () => {
/* Do what you want here */
// Continue this "loop" every 5000 ms
return Source.CONTINUE;
// Or remove it
return Source.REMOVE;
}, Priority.LOW);
Note: The Timeout is set as Priority.LOW as it runs in background and should give priority to others tasks.
Upvotes: 1
Reputation: 7153
If you spend your time sleeping in a system call, there's won't be any appreciable difference from a performance perspective. That said, it probably makes sense to use the MainLoop approach for two reasons:
You're going to need to setup signal handlers so that your daemon can die instantaneously when it is given SIGTERM. If you call quit
on your main loop by binding SIGTERM
via Posix.signal
, that's probably going to be a more readable piece of code than checking that the sleep was successful.
If you ever decide to add complexity, the MainLoop will make it more straight forward.
Upvotes: 7