The code behind goCron
This is the code behind.
package main
import (
"fmt"
"os"
"time"
"github.com/robfig/cron"
)
func crontsk() {
c := cron.New()
c.AddFunc("@every 5s", addstamp)
c.AddFunc("@every 60s", cleardoc)
c.Start()
time.Sleep(time.Duration(1 << 63 - 1))
}
func addstamp() {
t := time.Now()
crondoc(t.Format("2006-01-02T15-04-05.000Z"))
}
func crondoc(msg string) {
file, err := os.OpenFile("log.txt", os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
fmt.Println(err.Error())
}
file.WriteString(msg + "\n")
defer file.Close()
}
func cleardoc() {
if err := os.Truncate("log.txt", 0); err != nil {
fmt.Println(err)
}
}
The Go web server uses this code to update the page:
timestamp, _ := ioutil.ReadFile("log.txt")
tpl.ExecuteTemplate(w, page, string(timestamp))
And this Javascrpt refresh the page every 5 seconds;
<script>
window.setInterval('refresh()', 5000);
function refresh() {
window.location.reload();
}
</script>