Skip to content

Commit

Permalink
systemd permanent user service/timer
Browse files Browse the repository at this point in the history
  • Loading branch information
inv2004 committed Dec 20, 2022
1 parent 58a4a33 commit 3500720
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 9 deletions.
5 changes: 3 additions & 2 deletions src/ttop.nim
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ proc isSave(): bool =
false

proc isEnable(): bool =
if paramCount() >= 1 and paramStr(1) in ["-on"]:
if paramCount() >= 1 and paramStr(1) in ["-on", "--on"]:
true
else:
false

proc isDisable(): bool =
if paramCount() >= 1 and paramStr(1) in ["-off"]:
if paramCount() >= 1 and paramStr(1) in ["-off", "--off"]:
true
else:
false
Expand All @@ -36,6 +36,7 @@ proc main() =
let ex = getCurrentException()
echo ex.msg
echo ex.getStackTrace()
quit 1

when isMainModule:
main()
68 changes: 61 additions & 7 deletions src/ttop/onoff.nim
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,70 @@ const descr = "ttop service snapshot collector"

const options = {poUsePath, poEchoCmd}

proc onoff*(enable: bool) =


proc createService(file: string, app: string) =
if fileExists file:
return
echo "create ", file
writeFile(file,
&"""
[Unit]
Description={descr}
[Service]
ExecStart={app} -s
[Install]
WantedBy=ttop.timer
""")

proc createTimer(file: string, app: string) =
if fileExists file:
return
echo "create ", file
writeFile(file,
&"""
[Unit]
Description={descr} timer
[Timer]
OnCalendar=minutely
[Install]
WantedBy=timers.target
""")

proc createConfig() =
let dir = getConfigDir().joinPath("systemd", "user")
if not dirExists dir:
createDir dir

let app = getAppFilename()
createService(dir.joinPath(&"{unit}.service"), app)
createTimer(dir.joinPath(&"{unit}.timer"), app)

proc deleteConfig() =
let dir = getConfigDir().joinPath("systemd", "user")

let cmd =
if enable:
&"systemd-run --user --on-calendar='{timer}' --unit='{unit}' --description='{descr}' {app} -s"
else:
&"systemctl --user stop '{unit}.timer'"
var file = dir.joinPath(&"{unit}.service")
echo "delete ", file
removeFile file
file = dir.joinPath(&"{unit}.timer")
echo "delete ", file
removeFile file

let (output, code) = execCmdEx(cmd, options = options)
proc onoff*(enable: bool) =
var output = ""
var code = 0
if enable:
createConfig()
let cmd = &"systemctl --user start '{unit}.timer' '{unit}.service'"
(output, code) = execCmdEx(cmd, options = options)
else:
let cmd = &"systemctl --user stop '{unit}.timer' '{unit}.service'"
(output, code) = execCmdEx(cmd, options = options)
deleteConfig()
echo output
if code != 0:
quit code
Expand Down

0 comments on commit 3500720

Please sign in to comment.