@@ -164,31 +164,74 @@ def stop_background_workers(
164
164
print (f"Error stopping all Celery workers: { error } " )
165
165
print (error .stderr )
166
166
167
- @classmethod
168
- def handle_startup (cls , name : str ):
167
+ def start_background_beat (self , log_level : LogLevel = "INFO" ):
168
+ """Start Celery beat using the 'celery --app=app beat' command.
169
+
170
+ Args:
171
+ log_level: The log level.
172
+
173
+ Returns:
174
+ The background process running Celery beat.
175
+ """
176
+
177
+ print ("Starting Celery beat." )
178
+
179
+ try :
180
+ process = subprocess .Popen ( # pylint: disable=consider-using-with
181
+ [
182
+ "celery" ,
183
+ f"--app={ self .app } " ,
184
+ "beat" ,
185
+ f"--loglevel={ log_level } " ,
186
+ ],
187
+ stdout = subprocess .DEVNULL ,
188
+ stderr = subprocess .DEVNULL ,
189
+ )
190
+ print ("Successfully started Celery beat." )
191
+
192
+ atexit .register (self .stop_background_beat , process )
193
+
194
+ return process
195
+
196
+ except subprocess .CalledProcessError as error :
197
+ print (f"Error starting Celery beat: { error } " )
198
+
199
+ return None
200
+
201
+ def stop_background_beat (self , process : subprocess .Popen ):
202
+ """Stop a Celery beat process.
203
+
204
+ Args:
205
+ process: The process to stop.
206
+ """
207
+
208
+ print ("Stopping Celery beat." )
209
+
210
+ try :
211
+ process .terminate ()
212
+ print ("Successfully stopped Celery beat." )
213
+
214
+ except Exception as ex : # pylint: disable=broad-exception-caught
215
+ print (f"Error stopping Celery beat: { ex } " )
216
+
217
+ def handle_startup (self ):
169
218
"""Handle the startup procedure of a Celery app.
170
219
171
220
Examples:
172
221
```
173
- import os
174
- from codeforlife.apps import CeleryApplication
222
+ from codeforlife.apps import CeleryApplication, DjangoApplication
175
223
176
- # Make sure to set this before starting the Celery app !
177
- os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings" )
224
+ # Make sure to set up Django before starting!
225
+ DjangoApplication.setup( )
178
226
179
- celery_app = CeleryApplication.handle_startup(__name__ )
227
+ celery_app = CeleryApplication() .handle_startup()
180
228
```
181
229
182
- Args:
183
- name: The name of the file calling this function.
184
-
185
230
Returns:
186
- An instance of a Celery app .
231
+ The Celery app instance for convenience .
187
232
"""
188
233
189
- app = cls ()
190
-
191
- if name == "__main__" :
192
- app .start_background_workers ()
234
+ self .start_background_workers ()
235
+ self .start_background_beat ()
193
236
194
- return app
237
+ return self
0 commit comments