def test_mock_task(self, mock_run): assert add.delay(1, 1) add.delay.assert_called_once_with(1, 1) assert add.delay(1, 2) assert add.delay.call_count == 2 assert add.delay(2, 3) assert add.delay.call_count == 3
def register_webhook(): content = request.json if content["type"] == "confirmation": return webhook_return_code else: print("sending task to celery") add.delay(content) print("sending ok") return "ok"
def temp(): # synchronous print(add(4, 4)) # Asynchronous task = add.delay(4, 4) print(task) print(AsyncResult(task.task_id).get()) # synchronous print(add.delay(4, 4).get())
def on_get(self, req, resp, number): task = add.delay(int(number), int(number)) resp.status = falcon.HTTP_200 result = {'task_id': task.id} resp.body = json.dumps(result)
def arrange_tasks(): # normal call # add(0, 10) # send task message add.delay(1, 10) add.apply_async((2, 10)) # executes 10 seconds from now add.apply_async((3, 10), countdown=5) # executes 10 seconds from now - eta add.apply_async((4, 10), eta=datetime.utcnow() + timedelta(seconds=6)) # linking(callbacks / errbacks) add.apply_async((5, 10), link=add.s(7))
def test_celery_easy(self): """Test that the ``add`` task runs with no errors, and returns the correct result.""" from tasks import add result = add.delay(8, 8) self.assertEquals(result.get(), 16) self.assertTrue(result.successful())
def func(a, b): print("{}:::{}=>{}".format(threading.current_thread(), a, b)) # raise KeyError result = add.delay(a, b) # while not result.ready(): # time.sleep(1) # time.sleep(random.randint(1, 10)) print("task done:{}".format(result.get()))
def calculate(number1, number2): sum = add.delay(number1, number2) # database, collection, id Insert('pending', 'pending_task', sum.id) params = {"id": sum.id, "status": 200} return jsonify(params)
def test_celery(request): result = add.delay(7, 6) result_sum = result.get() return render(request, 'celerytest/test.html', { 'result': result, 'ready': result.ready(), 'sum': result_sum, })
def index(request): errors = [] print request.method if request.method == 'POST': a = request.POST['a'] b = request.POST['b'] task = add.delay(a, b) return render(request, 'success.html', {'task': task}) return render(request, 'index.html', {'errors': errors})
def main(): a1 = time.time() print('start task...') result = add.delay(10, 20) print('end task...') #import pdb;pdb.set_trace() print(result.ready()) a2 = time.time() print('共耗时:%s' % str(a2 - a1))
def test_delay(): result = add.delay(2, 2).get() log.info('add.delay 2, 2) = %s' % result) result = add.s(2, 2).delay().get() log.info('add.s(2, 2).delay().get() = %s' % result) result = add.s(2).delay(12).get() print(result)
def main(): result = add.delay(4, 4) job_id = str(result.id) got_result = app.AsyncResult(job_id) print job_id while not (got_result.ready()): time.sleep(1) print 'sleep 1, not ready' print got_result.ready() print str(got_result.get())
def hello(): result = add.delay(4, 4) while not result.ready(): time.sleep(1) print 'You will only see this if you\'re running this as debug' return json.dumps(result.info)
def init_work(request): """ A view to start a background job and redirect to the status page """ #job = do_work.delay() job = do_work.apply_async(task_id='my-bad-ass') print 'job.state ', job.state job.id add_result = add.delay(2,2) print 'add.state ', add_result.state return HttpResponseRedirect(reverse('poll_state') + '?job=' + job.id)
def main(): result = add.delay(4,4) job_id = str(result.id) got_result = app.AsyncResult(job_id) print job_id while not (got_result.ready()): time.sleep(1) print 'sleep 1, not ready' print got_result.ready() print str(got_result.get())
def index(request): test = models.test.objects.all().order_by('-id') if request.method == 'POST': print cache.get('mytext') sum=add.delay(int(request.POST['v1']),int(request.POST['v2'])) #return render(request,'index.html',{'sum':test[0].sum}) return HttpResponseRedirect('/index/') #HttpResponse('index.html',{'sum':sum}) else: cache.set('mytext','Hello redis') return render(request,'index.html',{'sum':test[0].sum})
def get(self): print datetime.datetime.now(), 'start' self.result = add.delay(9, 4) self.timeout_handler = None if self.result.ready(): self.write("Hello, world"+str(self.result.get())) self.finish() else: #这里的timeout时间大于任务时间和小于任务时间的表现是不一样的 add timeout 实现了一个非阻赛的 sleep #self.timeout_handler=tornado.ioloop.IOLoop.instance().add_timeout(time.time()+5, self.add) tornado.ioloop.IOLoop.instance().add_callback(self.add)
def test_celery(request): """test celery task""" cxt = {} cxt.update(csrf(request)) if request.method == 'POST': x = request.POST.get('paramx') y = request.POST.get('paramy') cxt.update({'paramx': x, 'paramy': y}) result = celery_add.delay(x, y) time.sleep(3) return render_to_response('test_celery.html', cxt)
def main(): print('main begin') result = add.delay(4, 9) while not result.ready(): time.sleep(1) print("working .....") print(result.get(timeout=1)) print('test div function for logging and retry') r = div(5, 2) print(r) print('main end')
def hello_celery(): result = add.delay(4,4) if result.ready(): print(result.result) else: print('not ready yet') wait_time = 0 while not result.ready(): sleep(0.1) wait_time += 0.1 print('result is ' + str(result.result)) print('waited %d seconds' % wait_time)
def post(self, request, *args, **kwargs): result = add.delay( request.data['config']['ipadd'], request.data['config']['username'], '/recetas/' + request.data['config']['receta'] + '/site.yml', request.data['config']['passwd'], request.data['config']['campos'], 4) print 'Task playbook finished? ', result.ready() print 'Task result: ', result.get() return Response(result.get(), status=status.HTTP_201_CREATED)
def ajax_page(request): if request.method == "POST": print request.POST x = int(request.POST["x"]) y = int(request.POST["y"]) # status = 'error' result = celery_add.delay(x, y).get() # if result != 10: # status = 'success' # if x + y != 10: # status = 'success' # time.sleep(5) # return JsonResponse({'status': status, 'result': result}) return JsonResponse(result) return render(request, "frontpage/ajax_page.html")
def register(): start = time.time() result = add.delay(6, 6) print("taskID: %s " % result.id) while True: if result.ready(): try: print("result: ", result.get( timeout=1)) # 如果使用了后端存储 必须要调用get() or forget()来回收资源 except: # 如果任务出现异常进行回滚 result.traceback break print("耗时:%s 秒 " % (time.time() - start))
def handle_command(command, channel): """ Receives commands directed at the bot and determines if they are valid commands. If so, then acts on teh commands. If not, returns back what it needs for clarification. """ if 'help' in command: response = 'Potentially, do you need help deploying your infrastructure on the Oracle Cloud?' slack_client.api_call('chat.postMessage', channel=channel, text=response, as_user=True) elif 'yes' in command: response = 'I can do that! Please provide your tenancy_ocid, compartment_ocid, and user_ocid.' slack_client.api_call('chat.postMessage', channel=channel, text=response, as_user=True) elif 'tenancy_ocid' in command and 'user_ocid' in command and 'compartment_ocid' in command: command = command.split(',') tenancy_ocid = command[0].split('=')[1] compartment_ocid = command[1].split('=')[1] user_ocid = command[2].split('=')[1] slack_client.api_call('chat.postMessage', channel=channel, text='Job being processed', as_user=True) for value in command: key = value.split('=')[0] val = '"{0}"'.format(value.split('=')[1]) dir = os.path.expanduser('~/Automatic/terraform-oci-workshop') script = dir + '/env.sh' cmd = "echo 'export TF_VAR_{0}={1}' >> {2}".format( key, val, script) subprocess.call(cmd, shell=True) result = add.delay(channel)
print "mul.delay(x, y)={0}".format(result.get()) result = mul.apply_async((x, y), countdown=5) # Same as add.delay(2, 2) print result.id # message id print "mul.delay(x, y)={0}".format(result.get()) result = add.apply_async((2, 2)) print result.get() print 'result.successful(): {0}'.format(result.successful()) print result.state # SUCCESS # Enhance above, create/send mesage to queue name 'lopri' # add.apply_async((2, 2), queue='lopri', countdown=5) # get propagated error if any try: result = add.delay(x) result.get() # propagate=True by default except Exception as e: print '=========' print e # disable propagated error if any try: result = add.delay(x) result.get(propagate=False) except Exception as e: print '---------' print e print 'result.failed(): {0}'.format(result.failed()) print result.state # FAILURE # Canvas/subtask
from tasks import add results = [] results.append(add.delay(4,4)) results.append(add.delay(1,0)) results.append(add.delay(37337,1)) for result in results: print result.get()
#!/usr/bin/env python from tasks import add result = add.delay(2,3) print result.ready() print result.get(timeout=10) print result.ready()
def main(): res = add.delay(4,4) print res.get(timeout=1)
#!/usr/bin/env python # Run a few tasks for testing purposes... from tasks import fib, add res1 = add.delay(1,1) res2 = add.delay(2,2) res3 = add.delay(3,3) f1 = fib.delay(15) f2 = fib.delay(100) print res1.get() print res2.get() print res3.get() print f1.get() print f2.get()
import sys from tasks import add a = int(sys.argv[1]) b = int(sys.argv[2]) r = add.delay(a, b)
from tasks import add, sub if __name__ == '__main__': try: async_result = add.delay(2) except TypeError as ex: print(ex) async_result = sub.delay(2)
def celery_add(): add.delay(1,2) return "Add task complete"
#! /usr/bin/env python import sys print sys.version print sys.executable print sys.path from tasks import add for x in range(0,20): print x add.delay(1,x)
def add_start(): """Grabs the args from the URL, starts the task, then redirects to show progress.""" x = request.args.get('x', 2, type=int) y = request.args.get('y', 3, type=int) task = add.delay(x, y) return redirect('/progress?tid=' + task.id)
from tasks import add for x in range(10000): add.delay(x, x)
from tasks import add result = add.delay(3,6) a=result.collect() for key , res in a: print res
def home(request): test = add.delay(1, 1) print test.__dict__ return HttpResponse("OK=" + str(test.__dict__))
from tasks import add if __name__ == '__main__': for i in range(100): for j in range(100): add.delay(i,j)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Description: Using task definition in an example. """ __author__ = "Ariel Gerardo Rios ([email protected])" from tasks import add result = add.delay(4, 4) # putting in queue for async processing result.ready() # checks if task was processed result.get(timeout=1) # gets task result
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2016-10-29 23:08:37 # @Author : zhuguangzu ([email protected]) # @Link : http://blog.zhuguangzu.xyz # DESC : # @Version : $Id$ import os from tasks import add if __name__ == '__main__': for i in range(100): for j in range(100): add.delay(i, j)
# run_basic.py from tasks import add task1 = add.delay(2, 5) task2 = add.apply_async(args=[4, 2]) task3 = add.apply_async(kwargs={"x": 3, "y": 6}) print(" 작업 ID 조회 ".center(50, "=")) print(f" task1: {task1.id}") print(f" task2: {task2.id}") print(f" task3: {task3.id}") print(" 작업 완료여부 조회 ".center(50, "=")) print(f" task1: {task1.ready()}") print(f" task2: {task2.ready()}") print(f" task3: {task3.ready()}") print(" 결과 데이터 조회 (완료될때까지 Pause) ".center(50, "=")) print(f" task1: {task1.get()}") print(f" task2: {task2.get()}") print(f" task3: {task3.get()}") print(" 작업 완료여부 조회 ".center(50, "=")) print(f" task1: {task1.ready()}") print(f" task2: {task2.ready()}") print(f" task3: {task3.ready()}")
from django.test import TestCase # Create your tests here. from tasks import add add.delay(4, 4)
from tasks import add if __name__ == "__main__": result = add.delay(20, 30) print(result) print(result.forget()) print(result.ready())
import time from tasks import add # celery -A tasks worker -c 4 --loglevel=info t1 = time.time() result = add.delay(1, 2) print(result.get()) print(time.time() - t1)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Name: app.py Author: cyan Time: 2019/7/26 10:36 Desc: """ import time from tasks import add if __name__ == '__main__': print('start task...') result = add.delay(3, 5) print('end task...') print(result)
def test_add_with_incorrect_values_raises_type_error(self): self.assertRaises(add.delay("d", "d"))
from tasks import add print(">>> from tasks import add") print(">>> add(4, 4)") res = add(4, 4) print(repr(res)) print(">>> add.delay(4, 4)") res = add.delay(4, 4) print(repr(res)) print(">>> add.delay(4, 4).wait()") res = add.delay(4, 4).wait() print(repr(res))
from tasks import add # Call the redis task result = add.delay(4, 4) # Check if tasks is finished or not result.ready()
from tasks import add add.delay(4, 4)
""" __title__ = '' __author__ = 'Thompson' __mtime__ = '2018/10/20' # code is far away from bugs with the god animal protecting I love animals. They taste delicious. ┏┓ ┏┓ ┏┛┻━━━┛┻┓ ┃ ☃ ┃ ┃ ┳┛ ┗┳ ┃ ┃ ┻ ┃ ┗━┓ ┏━┛ ┃ ┗━━━┓ ┃ 神兽保佑 ┣┓ ┃ 永无BUG! ┏┛ ┗┓┓┏━┳┓┏┛ ┃┫┫ ┃┫┫ ┗┻┛ ┗┻┛ """ #报红也能执行 from tasks import add import time result = add.delay(4, 4) #不要直接 add(4, 4),这里需要用 celery 提供的接口 delay 进行调用 while not result.ready(): time.sleep(50) print('task done: {0}'.format(result.get()))
from tasks import add import time result = add.delay(10, 20) ready = result.ready() counter = 0 t = time.time() result.wait() print("it took {:4f} s to get the result {} from task".format(time.time() - t, result.get()))
def main(): while True: for i in range(10): add.delay(i, i) sleep.delay(random.randint(1, i)) error.delay("Something went wrong")
from tasks import add, wait_seconds import time _ok = False while True: result = add.delay(4, 4) result2 = add.delay(2, 9) # this is not the idea because we are generating synchronous communication # but helps to the example while not (result.ready() and result2.ready()): if not _ok: print('result 1: ' + str(result.ready())) print('result 2: ' + str(result2.ready())) _ok = True _ok = False print('result 1: ' + str(result.ready())) print('result 2: ' + str(result2.ready())) get = result.get(propagate=False) get2 = result2.get(propagate=False) print('Result of task ' + str(result) + ' is ' + str(get)) print('Result of task ' + str(result2) + ' is ' + str(get2)) time.sleep(1)
from tasks import add print '4 + 3 =' result = add.delay(4, 3) print result.get(timeout=10)
from tasks import add if __name__ == '__main__': add.delay(1, 2)
def test_add_with_correct_values(self): result = add.delay(1, 3) self.assertEqual(4, result.get())
def form_valid(self, form): x = form.cleaned_data.get('x') y = form.cleaned_data.get('y') total = add.delay(x, y) messages.success(self.request, 'Calculating the result...') return HttpResponse('your result is {}'.format(total.get(timeout=2)))