Background Tasks

New in version 1.4.

Run scripts in the background.

This module allows your workflow to execute longer-running processes, e.g. updating the data cache from a webservice, in the background, allowing the workflow to remain responsive in Alfred.

For example, if your workflow requires up-to-date exchange rates, you might write a script update_exchange_rates.py to retrieve the data from the relevant webservice, and call it from your main workflow script:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 from workflow import Workflow, ICON_INFO
 from workflow.background import run_in_background, is_running

 def main(wf):
     # Is cache over 1 hour old or non-existent?
     if not wf.cached_data_fresh('exchange-rates', 3600):
         run_in_background('update',
                           ['/usr/bin/python',
                            wf.workflowfile('update_exchange_rates.py')])

     # Add a notification if the script is running
     if is_running('update'):
         wf.add_item('Updating exchange rates...', icon=ICON_INFO)

     # max_age=0 will return the cached data regardless of age
     exchange_rates = wf.cached_data('exchage-rates', max_age=0)

     # Display (possibly stale) cached data
     if exchange_rates:
         for rate in exchange_rates:
             wf.add_item(rate)

     # Send results to Alfred
     wf.send_feedback()

 if __name__ == '__main__':
     wf = Workflow()
     wf.run(main)

For a working example, see Tutorial Part 2: Creating a Distribution-Ready Pinboard Workflow.

API

workflow.background.run_in_background(name, args, **kwargs)

Pickle arguments to cache file, then call this script again via subprocess.call().

Parameters:
Returns:

exit code of sub-process

Return type:

int

When you call this function, it caches its arguments and then calls background.py in a subprocess. The Python subprocess will load the cached arguments, fork into the background, and then run the command you specified.

This function will return as soon as the background.py subprocess has forked, returning the exit code of that process (i.e. not of the command you’re trying to run).

If that process fails, an error will be written to the log file.

If a process is already running under the same name, this function will return immediately and will not run the specified command.

workflow.background.is_running(name)

Test whether task is running under name

Parameters:name (unicode) – name of task
Returns:True if task with name name is running, else False
Return type:Boolean