我在使用systemd的manjaro linux(基于arch)。我想制作一个后台运行的守护程序,并以随机间隔(最多间隔10分钟)拍摄屏幕截图。

我正在使用Go,并且我有一个程序可以很好地运行,如果我构建它并从命令行运行它(请参见下文)。我已经为服务创建了一个.service文件(请参见下文),并已使用systemctl start screenshot启动它,并确认它正在使用systemctl is-active screenshot运行。但是,它不起作用。没有像我从命令行运行一样保存任何屏幕截图。

出于兴趣,我尝试使用nohup ./screenshot &运行它,它遇到了与守护程序相同的问题。

在后台使用日期包是否存在某种问题?还是可能是屏幕截图库?
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\n", 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")
    }
}

这是服务文件
[Unit]
Description=Random Screenshot Service

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

[Install]
WantedBy=multi-user.target

最佳答案

在Flimzy对我的问题发表评论之后,我就知道了。正如他所说,您不能运行systemd上依赖X的内容,所以我改为从我的.i3 / config文件自动运行它(我使用I3窗口管理器)。再次感谢Flimzy为我提供帮助。

10-07 13:49
查看更多