Python Flask – repeatedly call code every 30 seconds

I’ve created a Python Flask server which makes an SQL query to a database and plots the result to a Plot.ly chart. I now want to use Plotly’s streaming feature and have my chart update every x amount of seconds (undecided on frequency for now) but this will require the database to be queried for each update. Is there a way using Flask where I can call my queries using PyathenaJDBC at a certain interval?

Timer selector not firing but ONLY when called from delegate method

There once lived a class:

class Poo: UIViewController {

var timer = Timer()

func someFunctionInsideThisClass() {
    startTimer()
}

func startTimer() {
    print("Z216 - startTimer called!")
    timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: (#selector(Poo.updateTimer)), userInfo: nil, repeats: true)
}

@objc private func updateTimer() {
    print("Z216 - updateTimer called!")
}

}

This class WORKED TOTALLY FINE — the timer worked properly and BOTH print functions verified that.

However, an evil Prince added an additional class Moof that contained:

@objc protocol MoofDelegate: class {
    @objc optional func someOtherDelegateMethodIMadePriorThatWorksFine()
    @objc optional func startTimer()
}

class Moof : NSObject {

weak var delegate: MoofDelegate?

var syncQueue: DispatchQueue? = nil

override init() {
    super.init()
    syncQueue = DispatchQueue(label: "CanUExplainZAT")
    self.syncQueue!.sync() {
        print("Z216 - we are calling startTimer from Moof!")
        self.delegate!.startTimer!()
    }
} 
}

…and he also changed the Poo class to:

class Poo: UIViewController, MoofDelegate {

var timer = Timer()

private var moof: Moof! = Moof()

override func viewDidLoad() {
    super.viewDidLoad()

    moof.delegate = self
}

@objc func startTimer() {
    print("Z216 - startTimer called!")
    timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: (#selector(Poo.updateTimer)), userInfo: nil, repeats: true)
}

@objc private func updateTimer() {
    print("Z216 - updateTimer called!")
}

}

So now, instead of calling startTimer() from inside the Poo class, it’s being called from in the Moof class!

So, using this new delegate pattern, the print function inside startTimer() proves that startTimer() IS being called successfully, but… the wierd thing is… while it was working fine before, now the updateTimer() method is NOT subsequently called!

UPDATE:

I don’t really know why, but it works if I do this:

@objc func startTimer() {

    DispatchQueue.main.async(execute: {() -> Void in
        print("Z216 - startTimer called!")
        self.timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: (#selector(ViewController.updateTimer)), userInfo: nil, repeats: true)
    })
}

So, the theoretical question remains:

“Why would a timer instantiated inside a method, “method A” that works perfectly fine stop working (stop firing its own selector) only as a result of method A being changed to a delegate method (hint: It’s not because the method A is no longer being fired)… and then work again as a result of being enclosed in a DispatchQueue.main.async(execute: {() thingy.”

Can you explain that?

Navigate to next view controller after delay ios

I want to navigate to next view controller after a delay of 3 seconds. It happens, but it happens twice!. This is my code.

override func viewWillAppear(_ animated: Bool) {
    let authToken =  UserDefaults.standard.object(forKey:"token") as? String ?? ""


    if (authToken.characters.count == 0) {
        self.perform(#selector(ClassName.navigateToMobileScreen), with: nil, afterDelay: 3)
    }
}

I placed this in both viewDidLoad and viewDidAppear in different scenarios. What can be the problem with this?

How To Pause a Date Countdown in Excel [on hold]

I’m looking for VBA code to help me solve a tracking issue. Here’s the situation:

I have 30 days to complete a task. Let’s say I start 2/15/2018, my task is due 3/17/2018. But the clock pauses if I have to ask a question. Let’s say I ask the questions on the 17th… 2 days have passed, so I am down to 28. If the customer gets back to me on the 19th, my due date is now 3/19/18. If the customer took a full 30 days to get back to me, my new due date would be 28 days from the date they responded. We could go back and forth for days, months, etc. But each time I enter a new date, I need the due date to update, or pause based on whether or not I have an answer from them.

As you all might be wondering why on earth would i be interested in something like this… it’s a compliance thing. And I am trying to avoid an excel sheet with thousands of columns for dates. I’ve included a picture of what it looks like now.

Thank you all so much! enter image description here

Add multiple Count down timers one by one

I am trying to make an app for android that have multiple timers in one Listview or someting similar, when i can stop and start them individually. I was looking at this thread: Android: Multiple simultaneous count-down timers in a ListView , but with one diference.
In this thread, they add all timers on create, but i would like to add timer on list when i scan an nfc tag. So when i scan tag, intent opens, where I input time in field add click add. So now the new timer is on the list, where i can start it, or scan another nfc tag.

I already make that when i scan tag, intent opens, but then stoped 🙂
This is one similar app: https://play.google.com/store/apps/details?id=com.jee.timer

Thank you for help

Systemd timer and conditional service interaction

I’ve got a conditional systemd service foo.service with condition ConditionDirectoryNotEmpty=/tmp/foo. It’s a one-shot service to empty /tmp/foo.

This works correctly in isolation. If I start the service when /tmp/foo holds a file, the service runs and the file is removed. If not, the service is skipped. Either way, it runs in less than a second.

The problem arises when I try to start this service from an associated timer. The timer gets stuck in a broken state. systemctl list-timers shows that foo.timer has a NEXT entry in the past (!) and it fired one millisecond ago. Indeed, it appears to be continously firing. That’s of course not the timer setting:

[Timer]
OnUnitActiveSec=
OnUnitActiveSec=60s
Persistent=true

60 seconds is a lot more than one minute. The empty OnUnitActiveSec= line is intentional; it should clear any existing timer period.

Why is the timer going berserk? Why is it firing so often, why is the next time to fire in the past? Most importantly, how do I run a service once a minute, but only if needed?

systemd version 215, on Debian 8 (Armbian 5.30)

PHP timer that resets after x seconds

I trying to implement a timer to my website, as I want the timer to be the same for anyone entering, even if the timezones is different, I believe PHP works better than javascript, using time() maybe?

I’ll explain.
I want my timer to start at 50 seconds and go to 0 seconds, once it hits 0 the timer should reset. So, as mentioned, when I reload the page the timer should not reset. If the timer is e.g 34, and I reload the page, the timer should not reset back to 50, it should keep going, so if it takes 2 seconds to reload the page, the timer should be 32 in this case.

The timer should also be the same of everyone, if my friend in Russia is seeing 44 seconds, then my friend in Spain should also see 44 seconds.

I don’t have an example code as I simply don’t know how to do it.

Android Studio When clicking on imageview reduce time from the timer

This is the first time I am posting something on StackOverflow and that it only because I felt like this is one of those times I was not able to find what I needed from the vast Internet!

I am currently making an Android Application that is a game where I have an ball that is an imageview and each time I click on the ball, it moves to a random location with this method I’ve built:

private void changePos() {
    RelativeLayout gameLayout = findViewById(R.id.gameFrame);
    int frameHeight = gameLayout.getHeight();
    int frameWidth = gameLayout.getWidth();

    Random ballLocationY = new Random();
    int ballY = ballLocationY.nextInt(frameHeight);

    Random ballLocationX = new Random();
    int ballX = ballLocationX.nextInt(frameWidth);

    gameLayout.setY(ballY);
    gameLayout.setX(ballX);
}

So what I am struggling with is to reduce the timer with each click.
What I am trying to do is to reduce the timer with each click on the ball by a certain percentage.

Basically each time the user clicks on the ball, the timer starts off from 0 and counting upwards in seconds and milliseconds, and at 3 second mark the game is over.

This is the approach I am playing around with:

Runnable updateThreadTimer = new Runnable() {
    @Override
    public void run() {
        timeInMilliseconds = System.Clock.uptimeMillis() - startTime();
        updateTime = timeSwapBuff + timeInMilliseconds;
        int secs = (int) (updateTime / 1000);
        countDownText.setText("" + String.format("%2d", secs) + ":"
                                 + String.format("%3d", timeInMilliseconds));
        mHandler.postDelayed(this, 0);

        if (secs == 3 && timeInMilliseconds >= 3000) {
             timeSwapBuff += timeInMilliseconds;
             mHandler.removeCallbacks(updateThreadTimer);   
        }
    }
}

Variables necessary:

long startTime = 0L, timeInMilliseconds = 0L, timeSwapBuff = 0L, updateTime = 0L;

Handler mHandler = new Handler();

And then I have this in the Overridden onCreate method:

ball.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
         if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
             changePos();
             startTime = SystemClock.uptimeMillis();
             mHandler.postDelayed(updateThreadTimer, 0);
         }
         return true;
    }
}

So what I get is a timer that gets reset to 0 with each click on the button and starts again. And the timer displays in seconds and milliseconds: 0:0000, which is what I wanted, but I wanna reduce a certain percentage with each click and update the time.
So let’s say the counter starts with 3 seconds limit, after clicking on the ball couple of times, the timer should eventually come down and the game should fail if the timer goes above that time.

Obviously I have simplified the code quite a lot to get straight to the point.
I was wondering if anyone has any suggestions on how I could approach the problem I have.

I also want to apologize if the question is not asked properly, being the first time posting, leave suggestions if theres any hatin’ going on!

And I also want to mention it one more time, I’ve looked around for a solution like this, and the code I have put together is from lots of different sources, so I feel like I’ve done my research, and not being able to find something, hence I am turning to StackOverflow!

Tray Icon Opening Behind System Tray

I have a simple Java application that sets a reminder and displays a message on the System Tray when the timer ends.
When the user starts the program, a GUI is displayed that takes the user’s inputs and then its minimized to the System Tray and the user can right click it and select “Options” or “Exit”.

The Problem: When using Linux, the user right clicks on the Tray Icon and the menu opens up behind the System Tray meaning the user can not access “Options” or “Exit” and also, the “timer end” notification opens behind the System Tray.

How do I bring the menu and the notifications to the front?

private void initSystemTray() {
    //Declare the variables and the menus
    popup.add(menu1);
    popup.addSeparator();
    popup.add(exitItem);

    menu1.add(optionItem);

    trayIcon.setPopupMenu(popup);

    try {
        tray.add(trayIcon);
    }
    catch (Exception e) {

    }

}

public ReminderGUI() {

   if (SystemTray.isSupported()) {

       initSystemTray(); 
    //When the exit item is selected it closes the entire program
    exitItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            System.exit(0);
        }
    });

    //Displays the GUI to change the reminder settings
    optionItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            tray.remove(trayIcon);
            ReminderGUI myGUI = new ReminderGUI();
            myGUI.setVisible(true);
        }
    });

    menu1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            menu1.setEnabled(true);
        }
}); 
}               
}        

private void startJButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             

    String message;

    //Gets the reminder message inputed in the text area
    message = notificationJTextField.getText();

    //Timer task is created
    TimerTask timerTask = new TimerTask() {
    public void run() {
      timePassed++;
      //3600 seconds is one hour
      if (timePassed >= 3600) {       
         timerEnd = true;
         hourTimer.cancel();  
      }
      //When timer is done it displays the reminder message
      if (timerEnd) {
         trayIcon.displayMessage("End Timer", message, 
         TrayIcon.MessageType.INFO);

         timePassed = 0;
         timerEnd = false;

      }
    }
};
//If the 5 minutes reminder option is selected it shows the reminder message
// after 5 minutes

if (remindJComboBox.getSelectedItem() == "5 Minutes") {
        hourTimer.schedule(timerTask, 0, 83);
    }

Java timer when button pressed

I’m quite new to java and I’m trying to start a timer when I press a button but I can’t start it. I tried a few lines of code but nothing seems to work.

I’ve declared my labels,text fields and the timer:

private JTextField JTFHours;
private JTextField JTFMinutes;
private JTextField JTFSeconds;
private int ticks = 0;
private Timer timer;

After that in create GUI i have this

JLTimer = new JLabel("     DIGITAL TIMER     ");
jPRightTimer.add(JLTimer);
JTFHours = new JTextField(2);
jPRightTimer.add(JTFHours);
JLTimer = new JLabel(" : ");
jPRightTimer.add(JLTimer);
JTFMinutes = new JTextField(2);
jPRightTimer.add(JTFMinutes);
JLTimer = new JLabel("  :  ");
jPRightTimer.add(JLTimer);
JTFSeconds = new JTextField(2);
jPRightTimer.add(JTFSeconds);
timer = new Timer(1000, this);
timer.start();

In my event method i have this:

Object source = event.getSource();

if (source == jBRun) {
    JTFHours.setText(Integer.toString(ticks / 360));
    JTFMinutes.setText(Integer.toString(ticks / 60));
    JTFSeconds.setText(Integer.toString(ticks % 60));
    ticks = ticks + 1;
}

If i am pressing the run button the timer doesn`t start.