I
I
Ilya55272022-01-31 11:56:12
Java
Ilya5527, 2022-01-31 11:56:12

How to implement asynchrony in telegram bot?

Hello, I have a problem.
I need other users to be able to use it during the mailing in my bot so that the bot responds, so it is necessary to implement asynchrony, so here are the questions:
1) How to implement asynchrony in the telegram bot?
2) Are there any examples.
3) Is asynchrony in java done through separate threads or through something else?
Thanks for answers)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Roo, 2022-01-31
@xez

1. Just like in any other application.
2. Yes. You can google "Java async". Here is the first result: https://www.baeldung.com/java-asynchronous-programming
3. It will always be a separate thread (and how do you even imagine asynchronous execution without multithreading?!), but in modern java there are several options, in which you new Threadcan never write at all.

A
Alexander, 2022-02-01
@Arlekcangp

I'm not familiar with the telegram interface, but I think you need to create a thread whenever the bot receives a hit from a new user. And already this flow should answer it. At the end of the response, the thread must terminate itself. At the same time, the main thread can continue to receive new requests.
This is the simplest asynchronous processing scheme, but it has drawbacks. If many users access at the same time, a thread will be created for each. This can lead to serious degradation of OS performance or even exhaustion of resources. This problem can be solved in different ways. For example, as pointed out by Dmitry Roo - through the so-called Future or asynchronous tasks. But you can also use thread pool and queues. In my opinion, a solution with queues will be more controllable, but also more time consuming and requires experience. For the first step, you can use a simple scheme with the creation of a new thread for each new user.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question