Skip to content

Commit

Permalink
Refactor service start & stop
Browse files Browse the repository at this point in the history
Make it possible to shutdown an initialized service and start it again. Also add the option to get the current service run status
  • Loading branch information
DerAndereAndi committed Oct 16, 2024
1 parent ad27b3c commit 05a0543
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 5 deletions.
3 changes: 3 additions & 0 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ type ServiceInterface interface {
// shutdown the service
Shutdown()

// return if the service is running
IsRunning() bool

// add a use case to the service
AddUseCase(useCase UseCaseInterface)

Expand Down
45 changes: 45 additions & 0 deletions mocks/ServiceInterface.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

36 changes: 31 additions & 5 deletions service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,11 @@ type Service struct {
// defines wether a user interaction to accept pairing is possible
isPairingPossible bool

startOnce sync.Once
// return if the service is running
isRunning bool

mux sync.Mutex
mux sync.Mutex
muxRunning sync.Mutex
}

// creates a new EEBUS service
Expand Down Expand Up @@ -153,15 +155,39 @@ func (s *Service) Setup() error {

// Starts the service
func (s *Service) Start() {
s.startOnce.Do(func() {
s.connectionsHub.Start()
})
s.muxRunning.Lock()
defer s.muxRunning.Unlock()

// make sure we do not start twice while the service is already running
if s.isRunning {
return
}

s.connectionsHub.Start()
}

// Shutdown all services and stop the server.
func (s *Service) Shutdown() {
s.muxRunning.Lock()
defer s.muxRunning.Unlock()

// if the service is not running, we do not need to shut it down
if !s.isRunning {
return
}

// Shut down all running connections
s.connectionsHub.Shutdown()

s.isRunning = false
}

// return if the service is running
func (s *Service) IsRunning() bool {
s.muxRunning.Lock()
defer s.muxRunning.Unlock()

return s.isRunning
}

// add a use case to the service
Expand Down

0 comments on commit 05a0543

Please sign in to comment.