mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2025-11-29 02:42:51 +00:00
Refactor: Replace time.Sleep with sync.WaitGroup for reliable TgBot shutdown
Replaced the unreliable `time.Sleep(1 * time.Second)` in `service.StopBot()` with `sync.WaitGroup`. This ensures the Long Polling goroutine is explicitly waited for and reliably exits before the panel continues, preventing potential resource leaks and incomplete shutdowns during restarts. Changes: - Added `botWG sync.WaitGroup` variable. - Updated `service.StopBot()` to call `botWG.Wait()` instead of `time.Sleep()`. - Modified `Tgbot.OnReceive()` to correctly use `botWG.Add(1)` and `defer botWG.Done()` within the Long Polling goroutine. - Corrected the goroutine structure in `OnReceive()` to properly encapsulate all message handling logic.
This commit is contained in:
parent
bb78b9495a
commit
4c929a8bcc
1 changed files with 7 additions and 5 deletions
|
|
@ -44,6 +44,8 @@ var (
|
|||
botCancel context.CancelFunc
|
||||
// tgBotMutex protects concurrent access to botCancel variable
|
||||
tgBotMutex sync.Mutex
|
||||
// botWG waits for the OnReceive Long Polling goroutine to finish.
|
||||
botWG sync.WaitGroup
|
||||
|
||||
botHandler *th.BotHandler
|
||||
adminIds []int64
|
||||
|
|
@ -343,7 +345,7 @@ func StopBot() {
|
|||
|
||||
botCancel = nil
|
||||
// Giving the goroutine a small delay to exit cleanly.
|
||||
time.Sleep(1 * time.Second)
|
||||
botWG.Wait()
|
||||
logger.Info("Telegram bot successfully stopped.")
|
||||
}
|
||||
}
|
||||
|
|
@ -377,9 +379,6 @@ func (t *Tgbot) OnReceive() {
|
|||
params := telego.GetUpdatesParams{
|
||||
Timeout: 30, // Increased timeout to reduce API calls
|
||||
}
|
||||
|
||||
// updates, _ := bot.UpdatesViaLongPolling(context.Background(), ¶ms)
|
||||
|
||||
// --- GRACEFUL SHUTDOWN FIX: Context creation ---
|
||||
tgBotMutex.Lock()
|
||||
|
||||
|
|
@ -400,7 +399,10 @@ func (t *Tgbot) OnReceive() {
|
|||
|
||||
// Get updates channel using the context.
|
||||
updates, _ := bot.UpdatesViaLongPolling(ctx, ¶ms)
|
||||
|
||||
botWG.Add(1)
|
||||
go func() {
|
||||
defer botWG.Done()
|
||||
|
||||
botHandler, _ = th.NewBotHandler(bot, updates)
|
||||
botHandler.HandleMessage(func(ctx *th.Context, message telego.Message) error {
|
||||
delete(userStates, message.Chat.ID)
|
||||
|
|
|
|||
Loading…
Reference in a new issue