Skip to content

Hard stop worker by sending ctrl-c twice #86

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 23, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions django_tasks/backends/database/management/commands/db_worker.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import logging
import random
import signal
import sys
import time
from argparse import ArgumentParser, ArgumentTypeError
from types import FrameType
Expand Down Expand Up @@ -33,16 +34,22 @@ def __init__(
self.running_task = False

def shutdown(self, signum: int, frame: Optional[FrameType]) -> None:
if not self.running:
logger.warning(
"Received %s - shutting down immediately.", signal.strsignal(signum)
)
sys.exit(1)

logger.warning(
"Received %s - shutting down gracefully.", signal.strsignal(signum)
"Received %s - shutting down gracefully... (press Ctrl+C again to force)",
signal.strsignal(signum),
)

self.running = False

if not self.running_task:
# If we're not currently running a task, exit immediately.
# This is useful if we're currently in a `sleep`.
exit(0)
sys.exit(0)

def configure_signals(self) -> None:
signal.signal(signal.SIGINT, self.shutdown)
Expand Down Expand Up @@ -94,8 +101,11 @@ def start(self) -> None:
# If we're running in "batch" mode, terminate the loop (and thus the worker)
return None

# Wait before checking for another task
time.sleep(self.interval)
# If ctrl-c has just interrupted a task, self.running was cleared,
# and we should not sleep, but rather exit immediately.
if self.running:
# Wait before checking for another task
time.sleep(self.interval)
Comment on lines +106 to +108
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If ctrl-c has just interrupted a task, we should not sleep, but rather exit immediately.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Make sense to me - nice catch! Could that be immortalised as a comment?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought you might ask that :) I've added the comment.


def run_task(self, db_task_result: DBTaskResult) -> None:
"""
Expand Down
Loading