Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marbetschar/395dc945a06f7c0a60a04b67eb424de3 to your computer and use it in GitHub Desktop.
Save marbetschar/395dc945a06f7c0a60a04b67eb424de3 to your computer and use it in GitHub Desktop.
Vala: How to avoid time offsets caused by hibernation

Vala: How to avoid time offsets caused by hibernation

Use the prepare_for_sleep signal to calculate the time between suspend and resume.

Credits to @vjr for this tip!

How to run this code

  1. Install Vala Tester from elementary AppCenter
  2. Copy & paste all of the below code snippets in Vala Tester's code view
  3. Run the code in Vala Tester (click "▶️") - this will open a new application window
  4. Suspend & resume your computer
  5. Close the application window started by Vala Tester
  6. Now the sleep duration of your computer gets printed in Vala Tester's output view.
public class Application : Gtk.Application {
private LoginManager login_manager;
private GLib.DateTime? sleep_start_datetime = null;
construct {
try {
login_manager = GLib.Bus.get_proxy_sync (BusType.SYSTEM, "org.freedesktop.login1", "/org/freedesktop/login1");
login_manager.prepare_for_sleep.connect (on_prepare_for_sleep);
} catch(GLib.Error e) {
warning (e.message);
}
}
private void on_prepare_for_sleep (bool start) {
if (start) {
sleep_start_datetime = new GLib.DateTime.now_local ();
GLib.Timeout.add_seconds (1, on_resume);
}
}
private bool on_resume () {
if (sleep_start_datetime != null) {
var now = new GLib.DateTime.now_local ();
var sleep_duration_seconds = now.difference (sleep_start_datetime) / 1000000;
stdout.printf (@"Your Computer slept for $sleep_duration_seconds seconds!");
}
return GLib.Source.REMOVE;
}
protected override void activate () {
var main_window = new Gtk.ApplicationWindow (this);
main_window.show_all ();
}
public static int main (string[] args) {
var app = new Application ();
return app.run (args);
}
}
/**
* The PrepareForSleep() signal is sent right
* before (with the argument "true") or after (with the argument
* "false") the system goes down for suspend/hibernate.
* This may be used by applications to save data on disk,
* release memory, or do other jobs that should be
* done shortly before sleep.
*
* @see: https://freedesktop.org/wiki/Software/systemd/logind/#signals
*/
[DBus (name = "org.freedesktop.login1.Manager")]
interface LoginManager : GLib.Object {
public signal void prepare_for_sleep (bool start);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment