gitee.com/johng/gf@v1.4.7/third/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  	"time"
    12  
    13  	"gitee.com/johng/gf/third/golang.org/x/sys/windows/svc"
    14  	"gitee.com/johng/gf/third/golang.org/x/sys/windows/svc/debug"
    15  	"gitee.com/johng/gf/third/golang.org/x/sys/windows/svc/eventlog"
    16  )
    17  
    18  var elog debug.Log
    19  
    20  type myservice struct{}
    21  
    22  func (m *myservice) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) {
    23  	const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown | svc.AcceptPauseAndContinue
    24  	changes <- svc.Status{State: svc.StartPending}
    25  	fasttick := time.Tick(500 * time.Millisecond)
    26  	slowtick := time.Tick(2 * time.Second)
    27  	tick := fasttick
    28  	changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
    29  loop:
    30  	for {
    31  		select {
    32  		case <-tick:
    33  			beep()
    34  			elog.Info(1, "beep")
    35  		case c := <-r:
    36  			switch c.Cmd {
    37  			case svc.Interrogate:
    38  				changes <- c.CurrentStatus
    39  				// Testing deadlock from https://code.google.com/p/winsvc/issues/detail?id=4
    40  				time.Sleep(100 * time.Millisecond)
    41  				changes <- c.CurrentStatus
    42  			case svc.Stop, svc.Shutdown:
    43  				break loop
    44  			case svc.Pause:
    45  				changes <- svc.Status{State: svc.Paused, Accepts: cmdsAccepted}
    46  				tick = slowtick
    47  			case svc.Continue:
    48  				changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
    49  				tick = fasttick
    50  			default:
    51  				elog.Error(1, fmt.Sprintf("unexpected control request #%d", c))
    52  			}
    53  		}
    54  	}
    55  	changes <- svc.Status{State: svc.StopPending}
    56  	return
    57  }
    58  
    59  func runService(name string, isDebug bool) {
    60  	var err error
    61  	if isDebug {
    62  		elog = debug.New(name)
    63  	} else {
    64  		elog, err = eventlog.Open(name)
    65  		if err != nil {
    66  			return
    67  		}
    68  	}
    69  	defer elog.Close()
    70  
    71  	elog.Info(1, fmt.Sprintf("starting %s service", name))
    72  	run := svc.Run
    73  	if isDebug {
    74  		run = debug.Run
    75  	}
    76  	err = run(name, &myservice{})
    77  	if err != nil {
    78  		elog.Error(1, fmt.Sprintf("%s service failed: %v", name, err))
    79  		return
    80  	}
    81  	elog.Info(1, fmt.Sprintf("%s service stopped", name))
    82  }