The proper way to terminate export addon?

Hi,
I’m writing an addon for making ortographic online tilesets for Leaflet.js.
Demo here:
http://opendimension.org/projects/online_tiles_addon/index_tiles.html

Since this kind of rendering tasks can take lot of time (images can be 32000*32000 pixels or more), I need a clean way to terminate export if user decides to abort the task. However, I need to do some cleanup before the exit.

How should I implement that?
Can I use the Cancel button in the export dialog?

I know there is always Ctrl + C in terminal (I can handle KeyboardInterrupt) but is it the only way?

in modal operator, it’s possible to check for events (e.g. key press), then return {‘CANCELLED’}, but your script needs to run in “cycles” I guess.

Thanks, the keyword seems to be “modal operator”, didn’t know this. I’ll investigate and report back.

Shame on me, there was a templates for modal operator in the Blender’s text editor :frowning:
With timer and modal operator one can make a script that run until user terminates it with for example by hitting ESC. The template in question can be found from the text editor -> Templates -> Python -> Operator Modal Timer

Thanks for CoDEmanX for pointing to the right direction!