Stop recording video after 15seconds - c#

I am trying to stop video playback after 15 seconds but it's not working. Please suggest me how to achieve this?
CameraCaptureUI captureUI = new CameraCaptureUI();
captureUI.VideoSettings.Format = CameraCaptureUIVideoFormat.Mp4;
StorageFile videoFile = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Video);
if (videoFile == null)
{
// User cancelled photo capture
return;
}

Using System.Timers you can achieve that. I don't know much about the library you are using, but using Timer i assume you can do it pretty easily.
using System.Timers;
static void Main(string[] args)
{
Timer tmr = new Timer();
int seconds = 15; // Not needed, only for demonstration purposes
tmr.Interval = 1000 * (seconds); // Interval - how long will it take for the timer to elapse. (In milliseconds)
tmr.Elapsed += Tmr_Elapsed; // Subscribe to the event
tmr.Start(); // Run the timer
}
private static void Tmr_Elapsed(object sender, ElapsedEventArgs e)
{
// Stop the video
}

Related

How to delay a timer from running or start it based on current date time

I have console application am using as demo to an App, it prints "hello", based on the timespan its expected to alert the user. when its not yet the timespan, i want to delay the app from printing hello and resume when its time.
public static async void timeCounter(int delae)
{
//This is suppose to cause a delay but it instead initiate the
//TimerOperation_Tick method.
await Task.Delay(delae);
// timer countdown
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 1000; // 1 second
timer.Elapsed += new ElapsedEventHandler(TimerOperation_Tick);
timer.Start();
if (obj.SubmissionCheck == true)
{
timer.Stop();
}
}
/// the event subscriber
private static void TimerOperation_Tick(object e, ElapsedEventArgs args)
{
if (timeFrame != 0)
{
Console.WriteLine("hi" + timeFrame);
timeFrame --;
if (timeFrame < 1)
{
obj.SubmissionCheck = true;
nt.Remove(obj);
startNotification();
}
}
}
Try setting timer.Enabled = false; This will prevent the timer ticks from occurring.

c# -- How can I make a microsecond timer?

Can anyone help me?
How can I make a microsecond timer in c#?
Like other timers, I want to do Something in the timer body.
If you are familiar with Stopwatches setting the tick-frequency to micoseconds via:
Stopwatch stopWatch = new Stopwatch();
stopWatch.ElapsedTicks / (Stopwatch.Frequency / (1000L*1000L));
should solve your problem.
Here you can download MicroLibrary.cs:
http://www.codeproject.com/Articles/98346/Microsecond-and-Millisecond-NET-Timer
Example for your problem:
private int counter = 0;
static void Main(string[] args)
{
Program program = new Program();
program.MicroTimerTest();
}
private void MicroTimerTest()
{
MicroLibrary.MicroTimer microTimer = new MicroLibrary.MicroTimer();
microTimer.MicroTimerElapsed +=
new MicroLibrary.MicroTimer.MicroTimerElapsedEventHandler(OnTimedEvent);
microTimer.Interval = 1000; // Call micro timer every 1000µs (1ms)
microTimer.Enabled = true; // Start timer
System.Threading.Thread.Sleep(2000); //do smth 2 seconds
microTimer.Enabled = false; // Stop timer (executes asynchronously)
Console.ReadLine();
}
private void OnTimedEvent(object sender,
MicroLibrary.MicroTimerEventArgs timerEventArgs)
{
// Do something every ms
Console.WriteLine(++counter);
}
}
}
System.Threading.Thread.SpinWait
is also essential for implementing this 'MicroTimer' lo-level class purpose.

How to trigger an event every specific time interval in C#?

the timer needs to be run as a thread and it will trigger an event every fixed interval of time. How can we do it in c#?
Here's a short snippet that prints out a message every 10 seconds.
using System;
public class AClass
{
private System.Timers.Timer _timer;
private DateTime _startTime;
public void Start()
{
_startTime = DateTime.Now;
_timer = new System.Timers.Timer(1000*10); // 10 seconds
_timer.Elapsed += timer_Elapsed;
_timer.Enabled = true;
Console.WriteLine("Timer has started");
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
TimeSpan timeSinceStart = DateTime.Now - _startTime;
string output = string.Format("{0},{1}\r\n", DateTime.Now.ToLongDateString(), (int) Math.Floor( timeSinceStart.TotalMinutes));
Console.Write(output);
}
}
Use one of the multiple timers available. Systme.Timer as a generic one, there are others dpending on UI technology:
System.Timers.Timer
System.Threading.Timer
System.Windows.Forms.Timer
System.Web.UI.Timer
System.Windows.Threading.DispatcherTimer
You can check Why there are 5 Versions of Timer Classes in .NET? for an explanation of the differences.
if you need something with mroore precision (down to 1ms) you an use the native timerqueues - but that requies some interop coding (or a very basic understanding of google).
I prefer using Microsoft's Reactive Framework (Rx-Main in NuGet).
var subscription =
Observable
.Interval(TimeSpan.FromSeconds(1.0))
.Subscribe(x =>
{
/* do something every second here */
});
And to stop the timer when not needed:
subscription.Dispose();
Super easy!
You can use System.Timers.Timer
Try This:
class Program
{
static System.Timers.Timer timer1 = new System.Timers.Timer();
static void Main(string[] args)
{
timer1.Interval = 1000;//one second
timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Tick);
timer1.Start();
Console.WriteLine("Press \'q\' to quit the sample.");
while (Console.Read() != 'q') ;
}
static private void timer1_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
//do whatever you want
Console.WriteLine("I'm Inside Timer Elapsed Event Handler!");
}
}

Running a task in windows service

I am making a windows service and one of its task is to ask for a free disk space every 1 hour, I know how to get the free space when the service starts but how to check for it every 1 hour?
Use a Timer like System.Timers.Timer:
var timer = new System.Timers.Timer();
timer.Elapsed += new ElapsedEventHandler(TimerElapsed);
timer.Interval = 60 * 60 * 1000; // 1 hour
timer.Enabled = true;
...
private static void TimerElapsed(object source, ElapsedEventArgs e)
{
// check disk space
}
Start thread:
while(true){
getFreeSpace();
Sleep(3600*1000);
};

Execute specified function every X seconds

I have a Windows Forms application written in C#. The following function checks whenever printer is online or not:
public void isonline()
{
PrinterSettings settings = new PrinterSettings();
if (CheckPrinter(settings.PrinterName) == "offline")
{
pictureBox1.Image = pictureBox1.ErrorImage;
}
}
and updates the image if the printer is offline. Now, how can I execute this function isonline() every 2 seconds so when I unplug the printer, the image displayed on the form (pictureBox1) turns into another one without relaunching the application or doing a manual check? (eg. by pressing "Refresh" button which runs the isonline() function)
Use System.Windows.Forms.Timer.
private Timer timer1;
public void InitTimer()
{
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 2000; // in miliseconds
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
isonline();
}
You can call InitTimer() in Form1_Load().
.NET 6 has added the PeriodicTimer class.
var periodicTimer= new PeriodicTimer(TimeSpan.FromSeconds(1));
while (await periodicTimer.WaitForNextTickAsync())
{
// Place function in here..
Console.WriteLine("Printing");
}
You can run it in the background with this:
async Task RunInBackground(TimeSpan timeSpan, Action action)
{
var periodicTimer = new PeriodicTimer(timeSpan);
while (await periodicTimer.WaitForNextTickAsync())
{
action();
}
}
RunInBackground(TimeSpan.FromSeconds(1), () => Console.WriteLine("Printing"));
The main advantage PeriodicTimer has over a Timer.Delay loop is best observed when executing a slow task.
using System.Diagnostics;
var stopwatch = Stopwatch.StartNew();
// Uncomment to run this section
//while (true)
//{
// await Task.Delay(1000);
// Console.WriteLine($"Delay Time: {stopwatch.ElapsedMilliseconds}");
// await SomeLongTask();
//}
//Delay Time: 1007
//Delay Time: 2535
//Delay Time: 4062
//Delay Time: 5584
//Delay Time: 7104
var periodicTimer = new PeriodicTimer(TimeSpan.FromMilliseconds(1000));
while (await periodicTimer.WaitForNextTickAsync())
{
Console.WriteLine($"Periodic Time: {stopwatch.ElapsedMilliseconds}");
await SomeLongTask();
}
//Periodic Time: 1016
//Periodic Time: 2027
//Periodic Time: 3002
//Periodic Time: 4009
//Periodic Time: 5018
async Task SomeLongTask()
{
await Task.Delay(500);
}
PeriodicTimer will attempt to invoke every n * delay seconds, whereas Timer.Delay will invoke every n * (delay + time for method to run) seconds, causing execution time to gradually move out of sync.
The most beginner-friendly solution is:
Drag a Timer from the Toolbox, give it a Name, set your desired Interval, and set "Enabled" to True. Then double-click the Timer and Visual Studio (or whatever you are using) will write the following code for you:
private void wait_Tick(object sender, EventArgs e)
{
refreshText(); // Add the method you want to call here.
}
No need to worry about pasting it into the wrong code block or something like that.
Threaded:
/// <summary>
/// Usage: var timer = SetIntervalThread(DoThis, 1000);
/// UI Usage: BeginInvoke((Action)(() =>{ SetIntervalThread(DoThis, 1000); }));
/// </summary>
/// <returns>Returns a timer object which can be disposed.</returns>
public static System.Threading.Timer SetIntervalThread(Action Act, int Interval)
{
TimerStateManager state = new TimerStateManager();
System.Threading.Timer tmr = new System.Threading.Timer(new TimerCallback(_ => Act()), state, Interval, Interval);
state.TimerObject = tmr;
return tmr;
}
Regular
/// <summary>
/// Usage: var timer = SetInterval(DoThis, 1000);
/// UI Usage: BeginInvoke((Action)(() =>{ SetInterval(DoThis, 1000); }));
/// </summary>
/// <returns>Returns a timer object which can be stopped and disposed.</returns>
public static System.Timers.Timer SetInterval(Action Act, int Interval)
{
System.Timers.Timer tmr = new System.Timers.Timer();
tmr.Elapsed += (sender, args) => Act();
tmr.AutoReset = true;
tmr.Interval = Interval;
tmr.Start();
return tmr;
}
Things have changed a lot with time.
You can use the solution below:
static void Main(string[] args)
{
var timer = new Timer(Callback, null, 0, 2000);
//Dispose the timer
timer.Dispose();
}
static void Callback(object? state)
{
//Your code here.
}
You can do this easily by adding a Timer to your form (from the designer) and setting it's Tick-function to run your isonline-function.
using System;
using System.Timers;
namespace SnirElgabsi
{
class Program
{
private static Timer timer1;
static void Main(string[] args)
{
timer1 = new Timer(); //new Timer(1000);
timer1.Elpased += (sender,e) =>
{
MyFoo();
}
timer1.Interval = 1000;//miliseconds
timer1.Start();
Console.WriteLine("press any key to stop");
Console.ReadKey();
}
private static void MyFoo()
{
Console.WriteLine(string.Format("{0}", DateTime.Now));
}
}
}

Categories