[英]How to automatically start and stop an influxdata process?
我最近使用设置了我的第一个 influxdb
https://www.influxdata.com/blog/getting-started-with-c-and-influxdb/
本教程。 我让应用程序运行并更改了程序以满足我的需要。 我知道您可以通过在 CMD 中键入“do.net run”来启动该过程,并通过在 CMD 中按 ctrl + c 来停止它。
但是如何通过 c# 代码自动启动和终止进程呢?
我希望该进程在被另一个 Programm 调用时运行,然后在 24 小时后终止。
提前致谢。
您的问题应该简化为如何启动和安排进程关闭。
可以使用定时器 class和ProcessStartInfo.CreateNoWindow class 。
在我的演示中, open(button)
将打开path
中的.txt
文件。
close(button)
将开始 5 秒倒计时以关闭notepad
程序。
您可以根据需要更改它。
这里使用的是.net 4.8框架winform。
当然,您也可以使用控制台应用程序来完成此操作。
下面是我的代码:
using System;
using System.Diagnostics;
using System.IO;
using System.Timers;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private static System.Timers.Timer aTimer;
private void button1_Click(object sender, EventArgs e)
{
StartApp(@"C:\Users\Administrator\Desktop");
}
/// <summary>
/// Start the process
/// </summary>
/// <param name="ArrayFolderPath">Need to open the path of the process folder, multiple paths are separated by ','; eg:d:\test,e:\temp</param>
private void StartApp(string ArrayFolderPath)
{
string[] foldersNamePath = ArrayFolderPath.Split(',');
foreach (string folderNamePath in foldersNamePath)
{
GetFolderApp(folderNamePath);
}
}
/// <summary>
/// Recursively traverse all exe files in the folder, this method can be further extended to other suffix files
/// </summary>
/// <param name="folderNamePath">Folder path</param>
private void GetFolderApp(string folderNamePath)
{
string[] foldersPath = Directory.GetDirectories(folderNamePath);
foreach (string folderPath in foldersPath)
{
GetFolderApp(folderPath);
}
string[] filesPath = Directory.GetFiles(folderNamePath);
foreach (string filePath in filesPath)
{
FileInfo fileInfo = new FileInfo(filePath);
//Open the file with the suffix .txt
if (fileInfo.Extension.Equals(".txt"))
{
Process.Start(filePath);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
SetTimer();
}
private static void SetTimer()
{
// Create a timer with a two second interval.
aTimer = new System.Timers.Timer(5000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = true;
aTimer.Enabled = true;
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
CloseApp("Notepad");
}
/// <summary>
/// Close the application
/// </summary>
/// <param name="ArrayProcessName">The application names are separated by ','</param>
private static void CloseApp(string ArrayProcessName)
{
string[] processName = ArrayProcessName.Split(',');
foreach (string appName in processName)
{
Process[] localByNameApp = Process.GetProcessesByName(appName);//Get all processes with program name
if (localByNameApp.Length > 0)
{
foreach (var app in localByNameApp)
{
if (!app.HasExited)
{
app.Kill();//close the process
}
}
}
}
}
}
}
Output:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.