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 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题