Reliable way to execute TypeScript code right before obsidian closes

I’m developing a plugin that makes automatic commits and I don’t seem to find a way so the plugin can make a last commit and push right before obsidian closes. I’ve tried on(name: 'quit', callback: (tasks: Tasks) => any, ctx?: any) but that does not work.

Can you share how you tried?

This seems to work for me

app.workspace.on('quit', (tasks) => tasks.add(async () => await sleep(10000)));

Just a general word of caution, and that is that you can’t really rely on any event regarding the end of an application. This simply did to the fact that you don’t know why it stopped. It could be an ordinary ending with the user quitting the application, but it could it also be terminated due to external reasons, or due to a critical bug, or maybe a priority shutdown, or …

In short, attaching to a quit event like suggested is a good suggestion, but I would strongly advise to build logic to possibly detect any abnormal exit and in any case do an initial commit when starting your plugin.

Another word of warning, any heavy tasks in the quit event are terminated after ~4 seconds and you can screw up other plugins because they don’t have enough time to react.
The event is it’s not guaranteed to be triggered (as pointed out by holroy) and does not run on mobile.

2 Likes