1#!/usr/bin/env python
2#
3# Copyright (C) 2017 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#      http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17import webapp2
18
19from webapp.src.proto import model
20
21from google.appengine.api import taskqueue
22
23
24class PeriodicScheduler(webapp2.RequestHandler):
25    """Main class for /tasks/schedule servlet.
26
27    This class creates a task, which creates schedules, in given period.
28    """
29
30    def get(self):
31        """Enqueues a scheduling task if scheduler is enabled."""
32        schedule_control = model.ScheduleControlModel.query()
33        schedule_control_dataset = schedule_control.fetch()
34        enabled = True
35        if schedule_control_dataset:
36            for schedule_control_data_tuple in schedule_control_dataset:
37                if (not schedule_control_data_tuple.schedule_name or
38                    schedule_control_data_tuple.schedule_name == "global"):
39                    enabled = schedule_control_data_tuple.enabled
40
41        if not enabled:
42            self.response.write(
43                "<pre>\nScheduler not enabled.\n</pre>")
44            return
45
46        task = taskqueue.add(
47            url="/worker/schedule_handler",
48            target="worker",
49            queue_name="queue-schedule",
50            transactional=False
51        )
52        self.response.write(
53            "<pre>\nScheduling task is enqueued. ETA {}\n</pre>".format(
54                task.eta))
55