Moving cancelling task code into its own function, refactored it and generalized it to prepare for an upcoming feature