github.com/cellofellow/gopkg@v0.0.0-20140722061823-eec0544a62ad/osext/winsvc/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  package main
     6  
     7  import (
     8  	"chai2010.gopkg/osext/winsvc/debug"
     9  	"chai2010.gopkg/osext/winsvc/eventlog"
    10  	"chai2010.gopkg/osext/winsvc/svc"
    11  	"fmt"
    12  	"time"
    13  )
    14  
    15  var elog debug.Log
    16  
    17  type myservice struct{}
    18  
    19  func (m *myservice) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) {
    20  	const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown | svc.AcceptPauseAndContinue
    21  	changes <- svc.Status{State: svc.StartPending}
    22  	fasttick := time.Tick(500 * time.Millisecond)
    23  	slowtick := time.Tick(2 * time.Second)
    24  	tick := fasttick
    25  	changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
    26  loop:
    27  	for {
    28  		select {
    29  		case <-tick:
    30  			beep()
    31  		case c := <-r:
    32  			switch c.Cmd {
    33  			case svc.Interrogate:
    34  				changes <- c.CurrentStatus
    35  			case svc.Stop, svc.Shutdown:
    36  				break loop
    37  			case svc.Pause:
    38  				changes <- svc.Status{State: svc.Paused, Accepts: cmdsAccepted}
    39  				tick = slowtick
    40  			case svc.Continue:
    41  				changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
    42  				tick = fasttick
    43  			default:
    44  				elog.Error(1, fmt.Sprintf("unexpected control request #%d", c))
    45  			}
    46  		}
    47  	}
    48  	changes <- svc.Status{State: svc.StopPending}
    49  	return
    50  }
    51  
    52  func runService(name string, isDebug bool) {
    53  	var err error
    54  	if isDebug {
    55  		elog = debug.New(name)
    56  	} else {
    57  		elog, err = eventlog.Open(name)
    58  		if err != nil {
    59  			return
    60  		}
    61  	}
    62  	defer elog.Close()
    63  
    64  	elog.Info(1, fmt.Sprintf("starting %s service", name))
    65  	run := svc.Run
    66  	if isDebug {
    67  		run = debug.Run
    68  	}
    69  	err = run(name, &myservice{})
    70  	if err != nil {
    71  		elog.Error(1, fmt.Sprintf("%s service failed: %v", name, err))
    72  		return
    73  	}
    74  	elog.Info(1, fmt.Sprintf("%s service stopped", name))
    75  }