@task
def clean_sessions():
 now = timezone.now()
 logger = clean_sessions.get_logger()
 chunk_size = config.SESSION_CLEANUP_CHUNK_SIZE
 if memcache.add(LOCK_ID, now.strftime('%c'), LOCK_EXPIRE):
  total_count = get_expired_sessions(now).count()
  delete_count = 0
  logger.info(('Deleting the %s of %s oldest expired sessions' % (chunk_size, total_count)))
  try:
   cursor = connection.cursor()
   delete_count = cursor.execute('\n                DELETE\n                FROM django_session\n                WHERE expire_date < NOW()\n                ORDER BY expire_date ASC\n                LIMIT %s;\n                ', [chunk_size])
  finally:
   logger.info(('Deleted %s expired sessions' % delete_count))
   memcache.delete(LOCK_ID)
   expired_sessions = get_expired_sessions(now)
   if expired_sessions.exists():
    clean_sessions.apply_async()
 else:
  logger.error(('The clean_sessions task is already running since %s' % memcache.get(LOCK_ID)))

@ task def clean_sessions ( ) : now = timezone . now ( ) logger = clean_sessions . get_logger ( ) chunk_size = config . SESSION_CLEANUP_CHUNK_SIZE if memcache . add ( LOCK_ID , now . strftime ( '%c' ) , LOCK_EXPIRE ) : total_count = get_expired_sessions ( now ) . count ( ) delete_count = 0 logger . info ( ( 'Deleting the %s of %s oldest expired sessions' % ( chunk_size , total_count ) ) ) try : cursor = connection . cursor ( ) delete_count = cursor . execute ( '\n                DELETE\n                FROM django_session\n                WHERE expire_date < NOW()\n                ORDER BY expire_date ASC\n                LIMIT %s;\n                ' , [ chunk_size ] ) finally : logger . info ( ( 'Deleted %s expired sessions' % delete_count ) ) memcache . delete ( LOCK_ID ) expired_sessions = get_expired_sessions ( now ) if expired_sessions . exists ( ) : clean_sessions . apply_async ( ) else : logger . error ( ( 'The clean_sessions task is already running since %s' % memcache . get ( LOCK_ID ) ) )
queue deleting expired session items without breaking poor mysql .