本文整理汇总了Python中times.now函数的典型用法代码示例。如果您正苦于以下问题:Python now函数的具体用法?Python now怎么用?Python now使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了now函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: enqueue_job
def enqueue_job(self, job):
"""
Move a scheduled job to a queue. In addition, it also does puts the job
back into the scheduler if needed.
"""
self.log.debug('Pushing {0} to {1}'.format(job.id, job.origin))
interval = job.meta.get('interval', None)
repeat = job.meta.get('repeat', None)
# If job is a repeated job, decrement counter
if repeat:
job.meta['repeat'] = int(repeat) - 1
job.enqueued_at = times.now()
job.save()
queue = self.get_queue_for_job(job)
queue.push_job_id(job.id)
self.connection.zrem(self.scheduled_jobs_key, job.id)
if interval:
# If this is a repeat job and counter has reached 0, don't repeat
if repeat is not None:
if job.meta['repeat'] == 0:
return
self.connection._zadd(self.scheduled_jobs_key,
times.to_unix(times.now()) + int(interval),
job.id)
示例2: create_board
def create_board(request):
bingo_board = _get_user_bingo_board(request)
game = bingo_board.game if bingo_board is not None else None
user = request.user
if bingo_board:
Game.objects.filter(id=bingo_board.game.id).update(
last_used=times.now())
return redirect(reverse(bingo, kwargs={
'board_id': bingo_board.board_id}))
elif request.POST:
create_form = CreateForm(
request.POST,
prefix="create",
game=game)
if create_form.is_valid():
with transaction.atomic():
ip = request.META['REMOTE_ADDR']
password = create_form.cleaned_data.get('password')
game_description = create_form.cleaned_data.get(
'description', '')
game = get_game(
site=get_current_site(request),
description=game_description,
create=True)
Game.objects.filter(id=game.id).update(
last_used=times.now())
# if the user is logged in, associate the board with
# the user, and ignore the password
# (so no other user can claim the board)
user = user if user.is_authenticated() else None
if user:
password = None
bingo_board = BingoBoard(
game=game, user=user, ip=ip, password=password)
bingo_board.save()
if USE_SSE:
_publish_num_users(game.site.id, game.num_users(),
game.num_active_users())
return redirect(reverse(bingo, kwargs={
'board_id': bingo_board.board_id}))
else:
reclaim_form = ReclaimForm(prefix="reclaim")
return render(
request,
"bingo/reclaim_board.html",
{
'reclaim_form': reclaim_form,
'create_form': create_form,
}
)
else:
return redirect(reverse(main))
示例3: perform_job
def perform_job(self, job):
"""Performs the actual work of a job. Will/should only be called
inside the work horse's process.
"""
self.procline('Processing %s from %s since %s' % (
job.func_name,
job.origin, time.time()))
try:
with death_penalty_after(job.timeout or Queue.DEFAULT_TIMEOUT):
job.started_at = times.now()
rv = job.perform()
# Pickle the result in the same try-except block since we need to
# use the same exc handling when pickling fails
job._result = rv
job._status = Status.FINISHED
job.ended_at = times.now()
keys = self.connection.hgetall(job._annotations)
p = self.connection.pipeline()
ingress = int(keys['ingress'])
egress = int(keys['egress'])
mean = float(keys['mean'])
delta = job.ended_at - job.started_at
delta = delta.seconds + (delta.microseconds / 1e6)
mean = (mean + delta) / (max(1, ingress + egress))
p.hincrby(job._annotations, 'ingress', amount=-1)
p.hincrby(job._annotations, 'egress', amount=1)
p.hset(job._annotations, 'mean', mean)
p.execute()
result_ttl = job.get_ttl(self.default_result_ttl)
pipeline = self.connection._pipeline()
if result_ttl != 0:
job.save(pipeline=pipeline)
job.cleanup(result_ttl, pipeline=pipeline)
pipeline.execute()
except:
# Use the public setter here, to immediately update Redis
job.status = Status.FAILED
self.handle_exception(job, *sys.exc_info())
return False
if rv is None:
self.log.info('Job OK')
else:
self.log.info('Job OK, result = %s' % (yellow(text_type(rv)),))
if result_ttl == 0:
self.log.info('Result discarded immediately.')
elif result_ttl > 0:
self.log.info('Result is kept for %d seconds.' % result_ttl)
else:
self.log.warning('Result will never expire, clean up result key manually.')
return True
示例4: test_clean_rq
def test_clean_rq(self):
r = get_redis_connection()
self.assertEqual(len(r.keys("rq:job:*")), 0)
r.hmset("rq:job:abc", {"bar": "baz"})
r.hmset("rq:job:def", {"created_at": times.format(times.now(), "UTC")})
r.hmset("rq:job:123", {"created_at": times.format(times.now() - timedelta(days=10), "UTC")})
self.assertEqual(len(r.keys("rq:job:*")), 3)
call_command("clean_rq")
self.assertEqual(len(r.keys("rq:job:*")), 2)
示例5: test_clean_rq
def test_clean_rq(self):
r = redis.Redis(**settings.REDIS)
self.assertEqual(len(r.keys('rq:job:*')), 0)
r.hmset('rq:job:abc', {'bar': 'baz'})
r.hmset('rq:job:def', {'created_at': times.format(times.now(), 'UTC')})
r.hmset('rq:job:123', {
'created_at': times.format(
times.now() - timedelta(days=10), 'UTC')})
self.assertEqual(len(r.keys('rq:job:*')), 3)
call_command('clean_rq')
self.assertEqual(len(r.keys('rq:job:*')), 2)
示例6: test_periodic_jobs_sets_ttl
def test_periodic_jobs_sets_ttl(self):
"""
Ensure periodic jobs set result_ttl to infinite.
"""
job = self.scheduler.schedule(times.now(), say_hello, interval=5)
job_from_queue = Job.fetch(job.id, connection=self.testconn)
self.assertEqual(job.result_ttl, -1)
示例7: get_jobs
def get_jobs(self, until=None, with_times=False):
"""
Returns a list of job instances that will be queued until the given time.
If no 'until' argument is given all jobs are returned. This function
accepts datetime and timedelta instances as well as integers representing
epoch values.
If with_times is True a list of tuples consisting of the job instance and
it's scheduled execution time is returned.
"""
def epoch_to_datetime(epoch):
return datetime.fromtimestamp(float(epoch))
if until is None:
until = "+inf"
elif isinstance(until, datetime):
until = times.to_unix(until)
elif isinstance(until, timedelta):
until = times.to_unix((times.now() + until))
job_ids = self.connection.zrangebyscore(self.scheduled_jobs_key, 0,
until, withscores=with_times,
score_cast_func=epoch_to_datetime)
if not with_times:
job_ids = zip(job_ids, repeat(None))
jobs = []
for job_id, sched_time in job_ids:
try:
job = Job.fetch(job_id, connection=self.connection)
if with_times:
jobs.append((job, sched_time))
else:
jobs.append(job)
except NoSuchJobError:
# Delete jobs that aren't there from scheduler
self.cancel(job_id)
return jobs
示例8: enqueue_job
def enqueue_job(self, job, set_meta_data=True):
"""Enqueues a job for delayed execution.
If the `set_meta_data` argument is `True` (default), it will update
the properties `origin` and `enqueued_at`.
If Queue is instantiated with async=False, job is executed immediately.
"""
# Add Queue key set
self.connection.sadd(self.redis_queues_keys, self.key)
if set_meta_data:
job.origin = self.name
job.enqueued_at = times.now()
if job.timeout is None:
job.timeout = self.DEFAULT_TIMEOUT
job.save()
if self._async:
self.push_job_id(job.id)
else:
job.perform()
job.save()
return job
示例9: events_current
def events_current(self):
now = times.now()
return self.events\
.filter(Event.starts_at < now)\
.filter(Event.ends_at > now)\
.filter(Event.cancelled_at == None)\
.order_by(Event.starts_at, Event.name)
示例10: enqueue_job
def enqueue_job(self, job, timeout=None, set_meta_data=True):
"""Enqueues a job for delayed execution.
If the `set_meta_data` argument is `True` (default), it will update
the properties `origin` and `enqueued_at`.
If Queue is instantiated with async=False, job is executed immediately.
"""
if set_meta_data:
job.origin = self.name
job.enqueued_at = times.now()
job.timeout = timeout # _timeout_in_seconds(timeout)
job.save()
if self._async:
p = self.connection.pipeline()
p.rpush(self.key, job.id)
p.rpush(self.key + ":blk", True)
p.incr(self.enqueues_count_key)
_, _, num_enqueued_jobs = p.execute()
job.num_enqueued_jobs = num_enqueued_jobs
else:
job.perform()
job.save()
return job
示例11: create_event
def create_event():
form = EventForm()
if form.validate_on_submit():
event = Event()
with db.transaction as session:
event.name = form.name.data
event.venue = form.venue.data
event.description = form.description.data
event.user = current_user
event.starts_at = times.to_universal(form.starts_at.data, current_user.timezone)
session.add(event)
with db.transaction:
event.contacts_invited_ids_str = form.contacts_invited_ids_str.data
send_email_invites(event)
return redirect(url_for('facebook_event', id=event.id))
else:
# default starts_at
td = datetime.timedelta(days=1)
dt = times.to_local(times.now(), current_user.timezone) + td
dt = datetime.datetime.combine(dt.date(), datetime.time(20, 00, 00))
form.starts_at.data = dt
return render_template('create_event.html', form=form)
示例12: date_cs
def date_cs(value):
"""Parses a Czech text to a date object."""
value = clean_whitespace(value)
match = re.search(r'(\d+)\s*\.?\s*(\w+)(\s+\d{2,4})?', value, re.U)
if match:
# day
day = int(match.group(1))
# month
try:
month = int(match.group(2))
except ValueError:
months = (
u'leden', u'únor', u'březen', u'duben',
u'květen', u'červen', u'červenec', u'srpen',
u'září', u'říjen', u'listopad', u'prosinec',
u'ledna', u'února', u'března', u'dubna',
u'května', u'června', u'července', u'srpna',
u'září', u'října', u'listopadu', u'prosince',
)
month = (months.index(match.group(2)) % 12) + 1
# year
if not match.group(3):
year = times.now().year
elif len(match.group(3)) == 2:
year = 2000 + int(match.group(3))
else:
year = int(match.group(3))
return datetime.date(year, month, day)
return None
示例13: date_time_year
def date_time_year(date, time, year=None, tz='Europe/Prague'):
"""Parses strings representing parts of datetime and combines them
together. Resulting datetime is in UTC.
"""
dt_string = u'{date} {time} {year}'.format(
date=date,
time=time,
year=year or times.now().year,
)
possible_formats = (
'%d. %m. %H:%M %Y',
'%d. %m. %H.%M %Y',
)
dt = None
for format in possible_formats:
try:
dt = datetime.datetime.strptime(dt_string, format)
except ValueError:
pass
else:
break
if dt:
return times.to_universal(dt, tz)
else:
raise ValueError(dt_string)
示例14: run
def run(self):
# delete old showtimes
query = Showtime.objects.filter(starts_at__lt=times.now())
count = query.count()
query.delete()
log.info('Cleanup: deleted %d old showtimes.', count)
# delete redundant showtimes
count = 0
for showtime in Showtime.objects.all():
with log.pass_on_exception():
duplicates = Showtime.objects.filter(
id__ne=showtime.id,
cinema=showtime.cinema,
starts_at=showtime.starts_at,
film_scraped__title_main=showtime.film_scraped.title_main
)
count += duplicates.count()
duplicates.delete()
log.info('Cleanup: deleted %d redundant showtimes.', count)
# delete redundant films
for film in Film.objects.all():
with log.pass_on_exception():
if not film.showtimes.count():
log.info('Cleanup: deleting redundant film %s.', film)
film.delete()
示例15: reclaim_board
def reclaim_board(request):
ip = request.META['REMOTE_ADDR']
game = get_game(site=get_current_site(request), create=False)
if game is not None:
Game.objects.filter(id=game.id).update(last_used=times.now())
bingo_board = _get_user_bingo_board(request)
if not bingo_board is None:
return redirect(reverse(bingo, kwargs={
'board_id': bingo_board.board_id}))
if request.POST:
reclaim_form = ReclaimForm(request.POST, game=game, prefix="reclaim")
if reclaim_form.is_valid():
bingo_board = reclaim_form.cleaned_data['bingo_board']
request.session['board_id'] = bingo_board.id
bingo_board.ip = ip
bingo_board.save()
return redirect(reverse(bingo, kwargs={'board_id':
bingo_board.board_id}))
else:
reclaim_form = ReclaimForm(prefix="reclaim")
create_form = CreateForm(prefix="create", game=game)
return render(request,
"bingo/reclaim_board.html", {
'reclaim_form': reclaim_form,
'create_form': create_form,
})