dounan9070 2018-02-19 10:05
浏览 257

尝试在systemd下运行可访问X服务器的服务

I'm using manjaro linux (arch based) with systemd. I want to make a daemon service that runs in the background and takes screenshots of my screen at random intervals, up to 10 minutes apart.

I'm using Go, and I have a program that works just fine if I build it and run it from the command line (see below). I've made a .service file (see below) for the service and I've started it with systemctl start screenshot and confirmed it's running with systemctl is-active screenshot. However, it doesn't work. No screenshots are being saved like if I run it from the command line.

Out of interest I tried running it with nohup ./screenshot & and it suffers from the same problem as my daemon attempt.

Is there some sort of problem with using the date package in the background? Or could it perhaps be the screenshot library?

screenshot.go

package main

import (
    "fmt"
    "image/png"
    "math/rand"
    "os"
    "time"

    "github.com/coreos/go-systemd/daemon"
    "github.com/vova616/screenshot"
)

func main() {
    daemon.SdNotify(false, "READY=1")
    i := 0
    for {
        r := rand.Intn(10)
        time.Sleep(time.Duration(r) * time.Minute)
        t := time.Now()
        year, month, day := t.Date()
        date := fmt.Sprintf("%d-%s-%d", year, month.String(), day)
        img, err := screenshot.CaptureScreen()
        if err != nil {
            fmt.Println(err)
            continue
        }
        hour, min, sec := t.Clock()
        stamp := fmt.Sprintf("%d:%d:%d", hour, min, sec)
        fmt.Printf("Taking screenshot %s
", stamp)
        f, err := os.Create(fmt.Sprintf("/home/dave/screenshot/%s/%s.png", date, stamp))
        if err != nil {
            fmt.Println(err)
            continue
        }
        err = png.Encode(f, img)
        if err != nil {
            fmt.Println(err)
            continue
        }
        err = f.Close()
        if err != nil {
            fmt.Println(err)
            continue
        }
        i++
        daemon.SdNotify(false, "WATCHDOG=1")
    }
}

and here is the service file

[Unit]
Description=Random Screenshot Service

[Service]
Type=notify
ExecStart=/home/dave/screenshot/screenshot
WatchdogSec=30s
Restart=on-failure

[Install]
WantedBy=multi-user.target
  • 写回答

1条回答 默认 最新

  • dongrouyuan5685 2018-02-19 11:40
    关注

    Following Flimzy's comment to my question I figured it out. As he stated you can't run stuff that relies on X from systemd, so instead I run it automatically from my .i3/config file (I use I3 window manager). Thanks again to Flimzy for helping me with that.

    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置