#!/usr/bin/env python


# https://twistedmatrix.com/documents/16.2.0/core/howto/defer.html

# task has no problem with stop() and .start()
# Why would it be getting lost in my code, I wonder?  >:(


from twisted.internet import reactor, defer, task
from pprint import pprint

import pendulum

def now():
    return pendulum.now().to_datetime_string()

def awake():
    print("awake", now())

def startTask(d):
    global t
    print("task awake, {0}".format(d), now())
    t = task.LoopingCall(awake)
    t.start(d)

def stopTask(d):
    global t
    print("STOP!", now())
    t.stop()
    reactor.callLater(d*2 + 1, startTask, d)

d = 2
reactor.callLater(1, startTask, d)
reactor.callLater(d * 3 + 1, stopTask, d + 1)


print("Stop the reactor in 40 seconds...", now())
reactor.callLater(40, reactor.stop)
print("starting the reactor", now())
reactor.run()

print("Done.", now())
print("Reactor has been safely shutdown.  :P")