user1419625
user1419625

Reputation:

Efficient daemon in Vala

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:

  1. Thread.usleep() or Posix.sleep()
  2. GLib.MainLoop + GLib.Timeout
  3. other?

I don't want it to eat too many resources when it's doing nothing..

Upvotes: 5

Views: 630

Answers (2)

SkyzohKey
SkyzohKey

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

apmasell
apmasell

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:

  1. 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.

  2. If you ever decide to add complexity, the MainLoop will make it more straight forward.

Upvotes: 7

Related Questions