本文整理汇总了Python中times.now函数的典型用法代码示例。如果您正苦于以下问题:Python now函数的具体用法?Python now怎么用?Python now使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了now函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:nvie,项目名称:rq-scheduler,代码行数:28,代码来源:scheduler.py
示例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))
开发者ID:allo-,项目名称:django-bingo,代码行数:58,代码来源:views.py
示例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
开发者ID:cwvh,项目名称:annotated_rq,代码行数:58,代码来源:worker.py
示例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)
开发者ID:bdyck,项目名称:feedhq,代码行数:9,代码来源:test_update_queue.py
示例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)
开发者ID:gjxlu,项目名称:feedhq,代码行数:11,代码来源:test_update_queue.py
示例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)
开发者ID:nvie,项目名称:rq-scheduler,代码行数:7,代码来源:test_scheduler.py
示例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
开发者ID:nvie,项目名称:rq-scheduler,代码行数:35,代码来源:scheduler.py
示例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
开发者ID:kennknowles,项目名称:rq,代码行数:25,代码来源:queue.py
示例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)
开发者ID:fdvoracek,项目名称:oleander,代码行数:7,代码来源:models.py
示例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
开发者ID:eranrund,项目名称:rq,代码行数:27,代码来源:queue.py
示例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)
开发者ID:fdvoracek,项目名称:oleander,代码行数:25,代码来源:events.py
示例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
开发者ID:apophys,项目名称:zitkino.cz,代码行数:32,代码来源:__init__.py
示例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)
开发者ID:apophys,项目名称:zitkino.cz,代码行数:25,代码来源:__init__.py
示例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()
开发者ID:apophys,项目名称:zitkino.cz,代码行数:27,代码来源:commands.py
示例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,
})
开发者ID:allo-,项目名称:django-bingo,代码行数:27,代码来源:views.py
示例16: count
def count(cls, pk, dimensions='_', metrics=None, at=False):
metrics = metrics or {}
metrics = isinstance(metrics, list) and dict([(k, 1) for k in metrics]) or metrics
try:
r = cls.hail_driver()
if not r:
return 0
set_number_name = 'hail_number'
set_number = r.get(set_number_name) or 0
if not set_number:
set_number = r.set(set_number_name, 0)
at = at or times.now()
if isinstance(at, str):
try:
at = datetime.datetime.fromtimestamp(float(at))
except ValueError:
pass # if at is not a float, ignore this
if isinstance(at, datetime.datetime):
at = at.ctime()
if isinstance(pk, cls):
pk = pk.getattr(cls.unique_key)
hit_key = '%s_%s_%s_%s' % (
cls.__name__, pk, at, random.randint(1, 1000))
r.sadd('hail_%s' % (set_number), hit_key)
r.set(hit_key, json.dumps(
(cls.__name__, pk, dimensions, metrics, at)))
except Exception as e:
return '%s' % e
return 'OK'
开发者ID:johann8384,项目名称:hailwhale,代码行数:29,代码来源:hail.py
示例17: enqueue_job
def enqueue_job(self, job, timeout=None, set_meta_data=True):
"""Enqueues a job for delayed execution.
When the `timeout` argument is sent, it will overrides the default
timeout value of 180 seconds. `timeout` may either be a string or
integer.
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()
if timeout:
job.timeout = timeout # _timeout_in_seconds(timeout)
else:
job.timeout = 180 # default
job.save()
if self._async:
self.push_job_id(job.id)
else:
job.perform()
job.save()
return job
开发者ID:MeTrina,项目名称:rq,代码行数:28,代码来源:queue.py
示例18: save
def save(self):
"""Persists the current job instance to its corresponding Redis key."""
key = self.key
obj = {}
obj['created_at'] = times.format(self.created_at or times.now(), 'UTC')
if self.func_name is not None:
obj['data'] = dumps(self.job_tuple)
if self.origin is not None:
obj['origin'] = self.origin
if self.description is not None:
obj['description'] = self.description
if self.enqueued_at is not None:
obj['enqueued_at'] = times.format(self.enqueued_at, 'UTC')
if self.ended_at is not None:
obj['ended_at'] = times.format(self.ended_at, 'UTC')
if self._result is not None:
obj['result'] = dumps(self._result)
if self.exc_info is not None:
obj['exc_info'] = self.exc_info
if self.timeout is not None:
obj['timeout'] = self.timeout
if self.result_ttl is not None:
obj['result_ttl'] = self.result_ttl
if self._status is not None:
obj['status'] = self._status
if self.meta:
obj['meta'] = dumps(self.meta)
self.connection.hmset(key, obj)
开发者ID:hungld,项目名称:rq,代码行数:31,代码来源:job.py
示例19: dump
def dump(self):
"""Returns a serialization of the current job instance"""
obj = {}
obj['created_at'] = times.format(self.created_at or times.now(), 'UTC')
if self.func_name is not None:
obj['data'] = dumps(self.job_tuple)
if self.origin is not None:
obj['origin'] = self.origin
if self.description is not None:
obj['description'] = self.description
if self.enqueued_at is not None:
obj['enqueued_at'] = times.format(self.enqueued_at, 'UTC')
if self.ended_at is not None:
obj['ended_at'] = times.format(self.ended_at, 'UTC')
if self._result is not None:
obj['result'] = dumps(self._result)
if self.exc_info is not None:
obj['exc_info'] = self.exc_info
if self.timeout is not None:
obj['timeout'] = self.timeout
if self.result_ttl is not None:
obj['result_ttl'] = self.result_ttl
if self._status is not None:
obj['status'] = self._status
if self._dependency_id is not None:
obj['dependency_id'] = self._dependency_id
if self.meta:
obj['meta'] = dumps(self.meta)
return obj
开发者ID:alonisser,项目名称:rq,代码行数:31,代码来源:job.py
示例20: today
def today(cls, queryset):
today = times.now().date()
return (
queryset.filter(starts_at__gt=today - timedelta(days=1))
.filter(starts_at__lt=today + timedelta(days=1))
.order_by('starts_at')
)
开发者ID:apophys,项目名称:zitkino.cz,代码行数:7,代码来源:models.py
注:本文中的times.now函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论