github.com/go-xe2/third@v1.0.3/golang.org/x/sys/windows/svc/example/service.go (about) 1 // Copyright 2012 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // +build windows 6 7 package main 8 9 import ( 10 "fmt" 11 "strings" 12 "time" 13 14 "github.com/go-xe2/third/golang.org/x/sys/windows/svc" 15 "github.com/go-xe2/third/golang.org/x/sys/windows/svc/debug" 16 "github.com/go-xe2/third/golang.org/x/sys/windows/svc/eventlog" 17 ) 18 19 var elog debug.Log 20 21 type myservice struct{} 22 23 func (m *myservice) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) { 24 const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown | svc.AcceptPauseAndContinue 25 changes <- svc.Status{State: svc.StartPending} 26 fasttick := time.Tick(500 * time.Millisecond) 27 slowtick := time.Tick(2 * time.Second) 28 tick := fasttick 29 changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted} 30 elog.Info(1, strings.Join(args, "-")) 31 loop: 32 for { 33 select { 34 case <-tick: 35 beep() 36 elog.Info(1, "beep") 37 case c := <-r: 38 switch c.Cmd { 39 case svc.Interrogate: 40 changes <- c.CurrentStatus 41 // Testing deadlock from https://code.google.com/p/winsvc/issues/detail?id=4 42 time.Sleep(100 * time.Millisecond) 43 changes <- c.CurrentStatus 44 case svc.Stop, svc.Shutdown: 45 break loop 46 case svc.Pause: 47 changes <- svc.Status{State: svc.Paused, Accepts: cmdsAccepted} 48 tick = slowtick 49 case svc.Continue: 50 changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted} 51 tick = fasttick 52 default: 53 elog.Error(1, fmt.Sprintf("unexpected control request #%d", c)) 54 } 55 } 56 } 57 changes <- svc.Status{State: svc.StopPending} 58 return 59 } 60 61 func runService(name string, isDebug bool) { 62 var err error 63 if isDebug { 64 elog = debug.New(name) 65 } else { 66 elog, err = eventlog.Open(name) 67 if err != nil { 68 return 69 } 70 } 71 defer elog.Close() 72 73 elog.Info(1, fmt.Sprintf("starting %s service", name)) 74 run := svc.Run 75 if isDebug { 76 run = debug.Run 77 } 78 err = run(name, &myservice{}) 79 if err != nil { 80 elog.Error(1, fmt.Sprintf("%s service failed: %v", name, err)) 81 return 82 } 83 elog.Info(1, fmt.Sprintf("%s service stopped", name)) 84 }