Skip to content

Instantly share code, notes, and snippets.

@oeway
Last active May 8, 2019 14:34
Show Gist options
  • Save oeway/3d2edd4f7978024fd219ee4e6764e6d1 to your computer and use it in GitHub Desktop.
Save oeway/3d2edd4f7978024fd219ee4e6764e6d1 to your computer and use it in GitHub Desktop.
<docs lang="markdown">
[TODO: write documentation for this plugin.]
</docs>
<config lang="json">
{
"name": "ResumableDemo",
"type": "native-python",
"version": "0.1.2",
"description": "[TODO: describe this plugin with one sentence.]",
"tags": [],
"ui": "",
"cover": "",
"inputs": null,
"outputs": null,
"flags": ["allow-detach", "single-instance"],
"icon": "extension",
"api_version": "0.1.3",
"env": "",
"requirements": [],
"dependencies": []
}
</config>
<script lang="python">
import time
import sys
import asyncio
import concurrent.futures
from imjoy import api
loop = asyncio.get_event_loop()
def heavy_computation(arg):
asyncio.set_event_loop(loop)
print('start computation task', arg)
for i in range(30):
time.sleep(1)
api.showStatus('running task '+str(arg) + ', remaining time: ' + str(30-i))
sys.stdout.flush()
class ImJoyPlugin():
def setup(self):
api.log('initialized')
self.task_count = 0
self.task_id = 0
self.executor = concurrent.futures.ThreadPoolExecutor(
max_workers=3,
)
def resume(self):
api.alert('plugin process resumed')
async def run(self, ctx):
self.task_count += 1
self.task_id += 1
if self.task_count > 3:
api.alert('hey, too many tasks, please try again later!')
task_id = self.task_id
await loop.run_in_executor(self.executor, heavy_computation, task_id)
self.task_count -= 1
api.alert(f'task {task_id} finished, remaining {self.task_count} tasks.')
api.export(ImJoyPlugin())
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment