blob: 2d0c4a56b377c8f8b7a14a7baccfab66b44b72c8 [file] [log] [blame]
Philipp Schradera9a79392023-03-25 13:28:31 -07001package background_task
Philipp Schraderc49eaf72023-02-26 16:56:52 -08002
3import (
4 "time"
5)
6
7// A helper to run a function in the background every ~10 minutes. Technically
8// can be used for a lot of different things, but is primarily geared towards
9// scraping thebluealliance.com.
Philipp Schradera9a79392023-03-25 13:28:31 -070010type BackgroundTask struct {
Philipp Schraderc49eaf72023-02-26 16:56:52 -080011 doneChan chan<- bool
12 checkStopped chan<- bool
13}
14
Philipp Schradera9a79392023-03-25 13:28:31 -070015func (scraper *BackgroundTask) Start(scrape func()) {
Philipp Schraderc49eaf72023-02-26 16:56:52 -080016 scraper.doneChan = make(chan bool, 1)
17 scraper.checkStopped = make(chan bool, 1)
18
19 go func() {
20 // Setting start time to 11 minutes prior so getRankings called instantly when Start() called
21 startTime := time.Now().Add(-11 * time.Minute)
22 for {
23 curTime := time.Now()
24 diff := curTime.Sub(startTime)
25
26 if diff.Minutes() > 10 {
27 scrape()
28 startTime = curTime
29 }
30
31 if len(scraper.doneChan) != 0 {
32 break
33 }
34
35 time.Sleep(time.Second)
36 }
37
38 scraper.checkStopped <- true
39 }()
40}
41
Philipp Schradera9a79392023-03-25 13:28:31 -070042func (scraper *BackgroundTask) Stop() {
Philipp Schraderc49eaf72023-02-26 16:56:52 -080043 scraper.doneChan <- true
44
45 for {
46 if len(scraper.checkStopped) != 0 {
47 close(scraper.doneChan)
48 close(scraper.checkStopped)
49 break
50 }
51 }
52}