Trigger background job using AJAX

I don’t think you need to worry about this running flag or unscheduling.
Since you are scheduling a one-time job that will run immediately there’s no reason to unschedule it.

You just need to check if a job with that name is scheduled or not and if it is (even if it is running at the moment) don’t do anything.

And yes, these jobs run on a different thread and as far as I know you can’t cancel them midway.

so the flow would be:

  • Click button
  • Run Ajax in JS
  • PHP Callback checks if it’s scheduled or not
  • If not, schedule it and return with wp_send_json_success().
    • Let it run
  • If it is, kill the ajax with wp_send_json_error()