-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
config: Rework
autosave
to be rearmed upon change
- Loading branch information
Showing
3 changed files
with
28 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,37 +1,49 @@ | ||
package config | ||
|
||
import ( | ||
"sync" | ||
"time" | ||
) | ||
|
||
var Autosave chan bool | ||
var autotime float64 | ||
|
||
// lock for autosave | ||
var autolock sync.Mutex | ||
var autotime chan float64 | ||
|
||
func init() { | ||
Autosave = make(chan bool) | ||
autotime = make(chan float64) | ||
} | ||
|
||
func SetAutoTime(a float64) { | ||
autolock.Lock() | ||
autotime = a | ||
autolock.Unlock() | ||
autotime <- a | ||
} | ||
|
||
func StartAutoSave() { | ||
go func() { | ||
var a float64 | ||
var t *time.Timer | ||
var elapsed <-chan time.Time | ||
for { | ||
autolock.Lock() | ||
a := autotime | ||
autolock.Unlock() | ||
if a <= 0 { | ||
break | ||
select { | ||
case a = <-autotime: | ||
if t != nil { | ||
t.Stop() | ||
for len(elapsed) > 0 { | ||
<-elapsed | ||
} | ||
} | ||
if a > 0 { | ||
if t != nil { | ||
t.Reset(time.Duration(a * float64(time.Second))) | ||
} else { | ||
t = time.NewTimer(time.Duration(a * float64(time.Second))) | ||
elapsed = t.C | ||
} | ||
} | ||
case <-elapsed: | ||
if a > 0 { | ||
t.Reset(time.Duration(a * float64(time.Second))) | ||
Autosave <- true | ||
} | ||
} | ||
time.Sleep(time.Duration(a * float64(time.Second))) | ||
Autosave <- true | ||
} | ||
}() | ||
} |