From 7afcc93507c310dc2336784ae8d37ce33cc0b5d6 Mon Sep 17 00:00:00 2001 From: Andrey Smirnov Date: Tue, 14 Jan 2014 14:11:28 +0400 Subject: [PATCH] Method Pause/Resume for Downloader. --- utils/download.go | 22 ++++++++++++++++++++++ utils/download_test.go | 8 ++++++++ utils/fake.go | 8 ++++++++ 3 files changed, 38 insertions(+) diff --git a/utils/download.go b/utils/download.go index 469aefbd..8c41aaed 100644 --- a/utils/download.go +++ b/utils/download.go @@ -15,6 +15,8 @@ import ( // Downloader is parallel HTTP fetcher type Downloader interface { Download(url string, destination string, result chan<- error) + Pause() + Resume() Shutdown() } @@ -28,6 +30,8 @@ type downloaderImpl struct { queue chan *downloadTask stop chan bool stopped chan bool + pause chan bool + unpause chan bool threads int } @@ -45,6 +49,8 @@ func NewDownloader(threads int) Downloader { queue: make(chan *downloadTask, 1000), stop: make(chan bool), stopped: make(chan bool), + pause: make(chan bool), + unpause: make(chan bool), threads: threads, } @@ -67,6 +73,20 @@ func (downloader *downloaderImpl) Shutdown() { } } +// Pause pauses task processing +func (downloader *downloaderImpl) Pause() { + for i := 0; i < downloader.threads; i++ { + downloader.pause <- true + } +} + +// Resume resumes task processing +func (downloader *downloaderImpl) Resume() { + for i := 0; i < downloader.threads; i++ { + downloader.unpause <- true + } +} + // Download starts new download task func (downloader *downloaderImpl) Download(url string, destination string, result chan<- error) { downloader.queue <- &downloadTask{url: url, destination: destination, result: result} @@ -127,6 +147,8 @@ func (downloader *downloaderImpl) process() { case <-downloader.stop: downloader.stopped <- true return + case <-downloader.pause: + <-downloader.unpause case task := <-downloader.queue: downloader.handleTask(task) } diff --git a/utils/download_test.go b/utils/download_test.go index 63de4aca..ae322130 100644 --- a/utils/download_test.go +++ b/utils/download_test.go @@ -45,6 +45,14 @@ func (s *DownloaderSuite) TestStartupShutdown(c *C) { } } +func (s *DownloaderSuite) TestPauseResume(c *C) { + d := NewDownloader(2) + defer d.Shutdown() + + d.Pause() + d.Resume() +} + func (s *DownloaderSuite) TestDownloadOK(c *C) { d := NewDownloader(2) defer d.Shutdown() diff --git a/utils/fake.go b/utils/fake.go index 532fdd5f..c4591197 100644 --- a/utils/fake.go +++ b/utils/fake.go @@ -88,3 +88,11 @@ func (f *FakeDownloader) Download(url string, filename string, result chan<- err // Shutdown does nothing func (f *FakeDownloader) Shutdown() { } + +// Pause does nothing +func (f *FakeDownloader) Pause() { +} + +// Resume does nothing +func (f *FakeDownloader) Resume() { +}