Philipp Schrader | c49eaf7 | 2023-02-26 16:56:52 -0800 | [diff] [blame^] | 1 | package background |
| 2 | |
| 3 | import ( |
| 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. |
| 10 | type BackgroundScraper struct { |
| 11 | doneChan chan<- bool |
| 12 | checkStopped chan<- bool |
| 13 | } |
| 14 | |
| 15 | func (scraper *BackgroundScraper) Start(scrape func()) { |
| 16 | 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 | |
| 42 | func (scraper *BackgroundScraper) Stop() { |
| 43 | 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 | } |