Add helper for efficiently spawning commands requiring internet access

It ensures that the command will be run at most once during the desired
`interval`, even if AwesomeWM restarts multiple times during this time.
This commit is contained in:
elenapan 2020-03-31 17:15:56 +03:00
parent 42324dcdb8
commit 80e73c57d8
2 changed files with 43 additions and 2 deletions

View file

@ -4,6 +4,7 @@
-- description (string)
-- icon_code (string)
local awful = require("awful")
local helpers = require("helpers")
-- Configuration
local key = user.openweathermap_key
@ -31,8 +32,7 @@ local weather_details_script = [[
fi
']]
-- Periodically get weather info
awful.widget.watch(weather_details_script, update_interval, function(widget, stdout)
helpers.remote_watch(weather_details_script, update_interval, "/tmp/awesomewm-evil-weather", function(stdout)
local icon_code = string.sub(stdout, 1, 3)
local weather_details = string.sub(stdout, 5)
weather_details = string.gsub(weather_details, '^%s*(.-)%s*$', '%1')

View file

@ -436,5 +436,46 @@ function helpers.screen_mask(s, bg)
return mask
end
-- Useful for periodically checking the output of a command that
-- requires internet access.
-- Ensures that `command` will be run only once during the desired
-- `interval`, even if awesome restarts multiple times during this time.
-- Saves output in `output_file` and checks its last modification
-- time to determine whether to run the command again or not.
-- Passes the output of `command` to `callback` function.
function helpers.remote_watch(command, interval, output_file, callback)
local run_the_thing = function()
-- Pass output to callback AND write it to file
awful.spawn.easy_async_with_shell(command.." | tee "..output_file, function(out) callback(out) end)
end
gears.timer {
timeout = interval,
call_now = true,
autostart = true,
single_shot = false,
callback = function()
awful.spawn.easy_async_with_shell("date -r "..output_file.." +%s", function(last_update, _, __, exitcode)
-- Probably the file does not exist yet (first time
-- running after reboot)
if exitcode == 1 then
run_the_thing()
return
end
local diff = os.time() - tonumber(last_update)
if diff > interval then
run_the_thing()
else
-- Pass the date saved in the file since it is fresh enough
awful.spawn.easy_async_with_shell("cat "..output_file, function(out) callback(out) end)
end
end)
end
}
end
return helpers