Backendless Support
 
Answered

Create Thread in Business Logic

I have an afterCreate event handler in my business logic that is synchronous. It needs to be synchronous as I have several tasks that need to be completed before sending the response to the user. BUT, there are also several tasks in the afterCreate that I'd like to do asynchronously (for instance sending an email or push notification can sometimes take a while).

1) What is the appropriate way to accomplish this? I don't think just creating a new Thread() is going work will it?

2) Are there any scenarios where an error could occur between when beforeCreate is called and the object is actually created in the data table? I ask this because if it is an extremely small possibility that an error can occur there, then I might move my synchronous tasks in the afterCreate over to the beforeCreate instead (I have it in afterCreate so I can ensure my updates are synched properly).

Thanks!

- Allen

Leave a Comment

Comments (5)

photo
1

It is possible to use `new Thread()` in the handlers' code, but you should be aware of tho limits:

1) Execution time limit - both sync and async actions will be terminated in case they do not complete in dedicated time

2) The thread count limit - https://backendless.com/pricing/backendless-cloud-pricing/

Of course in case it's Managed or Pro installation these limits do not apply and you can create threads as you need.

As to your second question, the possibility that beforeCreate handler proceeds, but the creation itself fails is not extremely small: for example, if some constraints fail, if data object count limit is exceeded, if permissions are denied (of this I'm not 100% sure though), and there's always a small probability of a software bug.

Hope this helps!

photo
1

That's awesome, we're on Pro, so just to confirm, I can spawn new Threads as I see fit and there's no limitations for us?

photo
1

What happens if I mess up and the thread never completes? Do you guys handle the runaway threads or do I risk slowly bringing everything down and exhausting the thread pool?

photo
1

The tasks will be terminated anyway after 2 hours, if I remember correctly. So no, you shouldn't be able to bring anything down with additional threads.

photo
1

awesome thanks!

photo