Windows service lifecycle

This article mainly introduces how to write a simple go program and register it as a windows system service. Article source code address: https://www.github.com/snowlyg/learns

Simple program

package main

import (
	"fmt"
	"time"
)

func main() {
	// 每隔 5 秒打印当前时间
	ticker := time.NewTicker(5 * time.Second)
	defer ticker.Stop()
	// for 循环阻塞程序主进程
	// ticker.C 通道每隔五秒会发送一个值
	for {
		<-ticker.C
		// 格式化时间
		now := time.Now().Format(time.RFC3339)
		fmt.Printf("当前时间:%s \n", now)
	}
}

Execute go run main.go in the terminal, and the current time will be printed every 5 seconds:

base_1.png

Package exe executable file

Run go build -o myservice.exe main.go to package the program into an exe execution file. A myservice.exe file will be generated in the project directory.