Skip to content
This repository has been archived by the owner on Dec 29, 2024. It is now read-only.

Commit

Permalink
refactor: replaced stop channel by context
Browse files Browse the repository at this point in the history
  • Loading branch information
Wittano committed Mar 19, 2024
1 parent e3d7a95 commit 8bff5aa
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 15 deletions.
6 changes: 4 additions & 2 deletions tasks/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package tasks

import (
"context"
"github.com/wittano/filebot/setting"
"time"
)

Expand All @@ -20,10 +21,11 @@ func RunTaskWithInterval(ctx context.Context, interval time.Duration, task taskR
for {
select {
case <-newCtx.Done():
break
return
case <-timer.C:
if err = task(newCtx); err != nil {
break
setting.Logger().Error("Error during execute scheduled task", err)
return
}
}
}
Expand Down
25 changes: 12 additions & 13 deletions watcher/watcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@ import (
type MyWatcher struct {
*fsnotify.Watcher
ctx context.Context
stop context.CancelFunc
mutex sync.Mutex
blocker chan bool
fileObserved map[string]string
}

func (w *MyWatcher) Close() (err error) {
w.mutex.Lock()
close(w.blocker)
w.stop()

err = w.Watcher.Close()
w.mutex.Unlock()
Expand All @@ -36,23 +36,26 @@ func NewWatcher(ctx context.Context) MyWatcher {
setting.Logger().Fatal("Failed initialized system file watcher", err)
}

blocker := make(chan bool)
newCtx, cancel := context.WithCancel(ctx)

return MyWatcher{
w,
ctx,
newCtx,
cancel,
sync.Mutex{},
blocker,
make(map[string]string),
}
}

func (w MyWatcher) ObserveFiles() {
func (w *MyWatcher) ObserveFiles() {
defer w.Close()

for {
select {
case <-w.ctx.Done():
return
case e, ok := <-w.Events:
if !ok {
w.blocker <- false
return
}

Expand All @@ -65,7 +68,6 @@ func (w MyWatcher) ObserveFiles() {
}
case err, ok := <-w.Errors:
if !ok {
w.blocker <- false
return
}

Expand All @@ -75,11 +77,8 @@ func (w MyWatcher) ObserveFiles() {
}

func (w *MyWatcher) WaitForEvents() {
if ok := <-w.blocker; !ok {
w.Close()

return
}
<-w.ctx.Done()
w.Close()
}

func (w *MyWatcher) AddFilesToObservable(config setting.Config) {
Expand Down

0 comments on commit 8bff5aa

Please sign in to comment.