Shut down writer once input is exhausted

* Call the close() method on the writer coroutine once the reader has been
  exhausted. This way, writers can catch the GeneratorExit exception and
  perform clean-up work and shut down gracefully.
* Add a stop() method to PeriodicThread which performs a graceful shutdown.
* Make the SQL writer call stop() on the worker when it's shutting down.

Change-Id: I8d589a29db4246ec71f6b2237e908c5b928202a8