Home > other >  Can not running a Go app (using os library) with cron job
Can not running a Go app (using os library) with cron job

Time:08-16

I had a problem when I tried run a Go app with cron job. It's seem that every func of os library can not execute in cron job. Here is my code. I've searched for a lot of time but haven't got any solotion yet.

Here is my code.

package main

import (
   "fmt"
   "os"
   "os/exec"
)

func main() {
   out, err := exec.Command("ls").Output()
   file, _ := os.Create("test.txt")
   _, err1 := file.Write([]byte(string(out)   "\n"))
   if err == nil && err1 == nil {
       fmt.Println("test")
   }
   fmt.Println(string(out))
}

Here is my cron job

* * * * * go run /root/code/main.go

Please help me fix this problem or any recommend to run a go app with cron job.

CodePudding user response:

By default, cron jobs are run with the root user, and probably there is no go binary in your root user's path. To check this, you can run.

# crontab -e
* * * * * whoami >> /tmp/debug.txt && where go && echo OK >> /tmp/debug.txt || echo ERROR >> /tmp/debug.txt

Which will show you user info and "Can I find go binary" information.

You can change the user who runs the cronjob

Better Way

As others said, it's not a good idea to run Go code with go run. Each time compiler needs to compile the code and run it.

If you run go build and run the produced executable, it'll simplify your workflow. Also, by default, go binaries are single binaries that contain all dependencies, which simplifies lots of things. You can just ./executable-name anywhere

  • Related