github.com/zhongdalu/gf@v1.0.0/third/golang.org/x/sys/windows/svc/example/manage.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  	"github.com/zhongdalu/gf/third/golang.org/x/sys/windows/svc"
    14  	"github.com/zhongdalu/gf/third/golang.org/x/sys/windows/svc/mgr"
    15  )
    16  
    17  func startService(name string) error {
    18  	m, err := mgr.Connect()
    19  	if err != nil {
    20  		return err
    21  	}
    22  	defer m.Disconnect()
    23  	s, err := m.OpenService(name)
    24  	if err != nil {
    25  		return fmt.Errorf("could not access service: %v", err)
    26  	}
    27  	defer s.Close()
    28  	err = s.Start("is", "manual-started")
    29  	if err != nil {
    30  		return fmt.Errorf("could not start service: %v", err)
    31  	}
    32  	return nil
    33  }
    34  
    35  func controlService(name string, c svc.Cmd, to svc.State) error {
    36  	m, err := mgr.Connect()
    37  	if err != nil {
    38  		return err
    39  	}
    40  	defer m.Disconnect()
    41  	s, err := m.OpenService(name)
    42  	if err != nil {
    43  		return fmt.Errorf("could not access service: %v", err)
    44  	}
    45  	defer s.Close()
    46  	status, err := s.Control(c)
    47  	if err != nil {
    48  		return fmt.Errorf("could not send control=%d: %v", c, err)
    49  	}
    50  	timeout := time.Now().Add(10 * time.Second)
    51  	for status.State != to {
    52  		if timeout.Before(time.Now()) {
    53  			return fmt.Errorf("timeout waiting for service to go to state=%d", to)
    54  		}
    55  		time.Sleep(300 * time.Millisecond)
    56  		status, err = s.Query()
    57  		if err != nil {
    58  			return fmt.Errorf("could not retrieve service status: %v", err)
    59  		}
    60  	}
    61  	return nil
    62  }